如何复制slice,map,interface

在Golang 里,可以使用内嵌的copy函数:

a := []int{1,2}
b := []int{3,4}
check := a
copy(a, b)
fmt.println(a, b, check)
// Output: [3 4] [3 4] [3 4]

下面的例子,和上面的例子刚好可以作为一个对比。其中等号并不复制切片的内容,只是复制了切片的引用。

a := [] int{1, 2}
b := [] int{3, 4}
check := a
a = b 
fmt.Println(a, b, check)
// Output: [3 4] [3, 4] [1, 2]

Golang 里复制map还只能用循环遍历它的keys,暂无其他好方法

a := map[string]bool{"A": true, "B": true}
b := make(map[string]bool)
for key, value := range a {
      b[key] = value
}

下面的方式也只是复制了引用

a := map[string]bool{"A": true, "B": true}
a := map[string]bool{"C": true, "D": true}
check := a
a = b
fmt.Println(a, b, check)
// Output : map[C:true D:true] map[C:true D:true] map[A:true B:true]

对于interface,没有一个内嵌的copy方法,深度拷贝并不存在

猜你喜欢

转载自blog.csdn.net/weixin_44328662/article/details/86533755