在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
Channel 发送和接收元素的本质是什么?
就是说 channel 的发送和接收操作本质上都是 “值的拷贝”,无论是从 sender goroutine 的栈到 chan buf,还是从 chan buf 到 receiver goroutine,或者是直接从 sender goroutine 到 receiver goroutine。 举一个例子: type user struct {
name string
age int8
}
var u = user{name: "Ankur", age: 25}
var g = &u
func modifyUser(pu *user) {
fmt.Println("modifyUser Received Vaule", pu)
pu.name = "Anand"
}
func printUser(u <-chan *user) {
time.Sleep(2 * time.Second)
fmt.Println("printUser goRoutine called", <-u)
}
func main() {
c := make(chan *user, 5)
c <- g
fmt.Println(g)
// modify g
g = &user{name: "Ankur Anand", age: 100}
go printUser(c)
go modifyUser(g)
time.Sleep(5 * time.Second)
fmt.Println(g)
}
运行结果: &{Ankur 25}
modifyUser Received Vaule &{Ankur Anand 100}
printUser goRoutine called &{Ankur 25}
&{Anand 100}
这里就是一个很好的 output
一开始构造一个结构体 u,地址是 0x56420,图中地址上方就是它的内容。接着把 main 程序里,先把 g 发送到 c,根据 再强调一次: Remember all transfer of value on the go channels happens with the copy of value.
参考: https://qcrao91.gitbook.io/go/channel/channel-fa-song-he-jie-shou-yuan-su-de-ben-zhi-shi-shi-mo https://www.cnblogs.com/bonelee/p/6056373.html |
请发表评论