3

go的值类型和引用类型1——传递和拷贝

 3 years ago
source link: https://studygolang.com/articles/33388
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.

首先,我们了解一些基本概念。

值类型:基本数据类型,数组,结构体,接口。

引用类型:map,slice,channel,func,指针。

函数调用时,传参数的方式:

值传递:拷贝值,递给函数的是变量的副本。

引用传递:拷贝指针,递给函数的是变量的指针。

函数内部,给新变量赋值的时候:

深拷贝:拷贝值,也叫值拷贝。

浅拷贝:拷贝指针。

拷贝规则:值类型一般都是深拷贝,引用类型都是浅拷贝。

传递规则:go里面都是值传递。

注意:切片在一定条件下也是值拷贝。

注意:针对结构体类型的变量,如果里面有指针字段。发生了拷贝,新变量的指针字段和源变量的指针字段指向相同的地址空间。

注意:如果结构体中有锁的话,记得重新初始化一个锁对象,否则会出现非预期的死锁,案例:

type User struct {
     mut sync.Mutex
     name string
 }

 func main() {
     u1 := &User{name: "test"}
     u1.Lock()
     defer u1.Unlock()
     tmp := *u1
     u2 := &tmp
     // u2.Mutex = sync.Mutex{} // 没有这一行就会死锁
     fmt.Printf("%#p\n", u1)
     fmt.Printf("%#p\n", u2)
     u2.Lock()
     defer u2.Unlock()
 }

$ go run test.go
c00000c060
c00000c080
fatal error: all goroutines are asleep - deadlock!

可以使用go vet test.go检查这个问题

有疑问加站长微信联系(非本文作者)

eUjI7rn.png!mobile

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK