在 go
中,当咱们以 new
或 &
的方式,建立一个 struct
的对象实例后(指针),若是直接使用赋值运算符,则像其余语言同样,会浅拷贝到一个新对象,两者指向的内存地址是相同的。go
并无相似 clone
这种 深拷贝
操做 关键字
,那如何简单快速的 深拷贝
一个 对象
?json
package main import ( "encoding/json" "fmt" ) type Student struct { Name string Age uint8 } func main() { // 深拷贝 将 stud1 对象 深拷贝出一个 stud2 // stud1 和 stud2 指向了两块内存地址 副本 stud1 := &Student{Name: "sqrtCat", Age: 35} // 为 tmp 分配新的内存地址 tmp := *stud1 // 将 tmp 的内存地址赋给指针变量 stud2 stud2 := &tmp stud2.Name = "bigCat" fmt.Printf("%+v\n%+v\n", stud1, stud2) // 浅拷贝 stud3 := &Student{Name: "sqrtCat", Age: 35} stud4 := stud3 stud4.Name = "bigCat" fmt.Printf("%+v\n%+v\n", stud3, stud4) }
还有个指针和变量的小例子能够参阅ui
package main import ( "fmt" ) type HelloService struct {} func (p *HelloService) Hello(request string, reply *string) error { // reply 是指针 // *reply 是指针指向的变量 *reply = "hello:" + request return nil } func main() { var reply1 *string//变量声明 reply1 = new(string)//空指针 初始化掉 reply2 := new(string)//声明+初始化 hs := new(HelloService) hs.Hello("sqrtcat", reply1) hs.Hello("bigcat", reply2) fmt.Printf("%v\n%v\n", *reply1, *reply2) }