24

Golang复制结构体

 4 years ago
source link: https://www.tuicool.com/articles/MvYrQrq
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Golang中复制结构体,可以使用赋值语句

package main

import (
    "fmt"
)

type Dog struct {
    age  int
    name string
}

func main() {
    roger := Dog{5, "Roger"}
    mydog := roger
    fmt.Printf("roger addr %p\n", &roger)
    fmt.Printf("mydog addr %p\n", &mydog)
    fmt.Println("Roger and mydog are equal structs?", roger == mydog)
    mydog.name = "piggie"
    fmt.Println("Roger and mydog are equal structs?", roger == mydog)
}

执行结果

roger addr 0xc000092000
mydog addr 0xc000092020
Roger and mydog are equal structs? true
Roger and mydog are equal structs? false

可以看出,roger跟mydog在内存中的地址不同。并且对mydog修改属性,对roger没有影响。

但是注意,这里的Dog结构体中的属性,都是值类型。如果是 引用类型 的话,复制的是 指针 ,而不是具体的值。所以通过赋值语句对结构体的拷贝,是 浅拷贝 。如需对引用类型属性进行深拷贝,可以通过手动创建的方式,或者使用实现了deepcopy功能的第三方包


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK