Golang中赋值会导致结构体复制
版权声明 本站原创文章 由 萌叔 发表
转载请注明 萌叔 | https://vearne.cc
前言
Golang很多语法特征都和C++非常相似, stuct对象的赋值操作,会导致struct被copy(浅拷贝)
test_copy.go
package main
import "fmt"
type Car struct{
Name string
Age int
XList []int
}
func main(){
a := Car{Name:"buick", Age: 10, XList:make([]int, 10)}
b := a
b.Age = 9
fmt.Printf("address a:%p\n", &a)
fmt.Printf("address b:%p\n", &b)
fmt.Println("----------------------")
fmt.Printf("Car a:%v\n", a)
fmt.Printf("Car a:%v\n", len(a.XList))
fmt.Printf("Car b:%v\n", b)
fmt.Printf("Car b:%v\n", len(b.XList))
}
输出
address a:0xc420068180
address b:0xc4200681b0
----------------------
Car a:{buick 10 [0 0 0 0 0 0 0 0 0 0]}
Car a:10
Car b:{buick 9 [0 0 0 0 0 0 0 0 0 0]}
Car b:10
可以看出a和b已经是完全不同的对象,对b的修改不会影响a