关于golang:go-深浅拷贝结构体对象

15次阅读

共计 901 个字符,预计需要花费 3 分钟才能阅读完成。

go 中,当咱们以 new& 的形式,创立一个 struct 的对象实例后(指针),如果间接应用赋值运算符,则像其余语言一样,会浅拷贝到一个新对象,二者指向的内存地址是雷同的。go 并没有相似 clone 这种 深拷贝 操作 关键字 ,那如何简略疾速的 深拷贝 一个 对象

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)
}

还有个指针和变量的小例子能够参阅

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)
}
正文完
 0