go 深/淺拷貝結構體對象

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)
}
相關文章
相關標籤/搜索