Deep copy things
译文:事物的深度复制
文档
安装
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] }
参考