golang拷贝函数总结

golang拷贝函数总结@TOC

golang直接内置函数append和copy都是浅拷贝,都不支持深拷贝,golang原生的内置函数没有像java那种深拷贝
append函数的拷贝,如果拷贝对象是结构体里面的数组,则拷贝的是数组的地址,如果是普通类型,则拷贝的是对象的值,如果是需要进行深拷贝,则需要自己复制对象,网上还有一种是通过序列化的方式来进行深拷贝,我没有测试成功
例子如下:
type Data struct {
Name []string
Value string
}

type Datas []Data

func main() {
datas := make([]Data,0,2)
copyActivities := make(Datas, 0, 2)

s1 := []string{"USA", "China",}                                                           
s2 := []string{ "Germany", "France"}                                                      
data1 := Data{s1, "1"}                                                                    
data2 := Data{s2, "2"}                                                                    
datas = append(datas, data1)                                                              
datas = append(datas, data2)                                                              
                                                                                          
b := &datas                                                                               
println("name:,",  data1.Name[0], "value:", data1.Value)                                  
println("name:,", data2.Name[0], "value:", data2.Value)                                   
copyActivities = append(copyActivities, (*b)[0])                                          
copyActivities = append(copyActivities, (*b)[1])                                          
                                                                                          
(*b)[0].Name[0] = "yyc"                                                                   
(*b)[0].Value = "10"                                                                      
println("name:,", copyActivities[0].Name[0], " value:",  copyActivities[0].Value)         

}

输出结果:
name:, USA value: 1
name:, Germany value: 2
name:, yyc value: 1

你可能感兴趣的:(golang)