Golang:deepcopy深複製工具庫
Deep copy things
譯文:事物的深度複製
文件
- github https://github.com/mohae/deepcopy
- pkg.go https://pkg.go.dev/github.com/mohae/deepcopy
安裝
go get github.com/mohae/deepcopy
示例
1、深複製切片
package main
import (
"fmt"
"github.com/mohae/deepcopy"
)
func main() {
var s1 = []int{1, 2, 3, 4, 5}
// 深複製切片
cpy := deepcopy.Copy(s1)
s2 := cpy.([]int)
// 修改s2的值
s2[0] = 6
fmt.Printf("s1: %v\n", s1)
// s1: [1 2 3 4 5]
fmt.Printf("s2: %v\n", s2)
// s2: [6 2 3 4 5]
}
2、深複製map
package main
import (
"fmt"
"github.com/mohae/deepcopy"
)
func main() {
var m1 = make(map[string]int)
m1["age"] = 10
// 深複製map
cpy := deepcopy.Copy(m1)
m2 := cpy.(map[string]int)
// 修改m2的值
m2["age"] = 12
fmt.Printf("m1: %v\n", m1)
// m1: map[age:10]
fmt.Printf("m2: %v\n", m2)
// m2: map[age:12]
}
回覆:【golang加群】加入golang開發者交流群