golang 复制对象的正确做法
需求
实际运用种,传参是一对象指针,现在如何最简便地复制一对象?
实现
坑:&* 先拿到值再指针?
package main import ( "time" "log" ) func main() { T1 := &TestS{1} T2 := &*T1 T2.a = 5 log.Print(T1) log.Print(T2) }
输出
2017/06/15 20:14:27 &{5}
2017/06/15 20:14:27 &{5}
正确:先*T 再&T
package main import ( "time" "log" ) func main() { T1 := &TestS{1} T2 := *T1 T3 := &T2 //改动地方 T3.a = 5 log.Print(T1) log.Print(T3) }
输出
2017/06/15 20:16:55 &{1}
2017/06/15 20:16:55 &{5}