为什么使用值传入,输出的是正确的,但使用指针传入,再取值,获得的值却是一样的呢????
```go
package main
import (
"fmt"
"time"
)
func tggg(p *int) {
fmt.Printf("p = %p, v = %d\n", p, *p)
}
func tggg1(t int) {
fmt.Printf("v = %d\n", t)
}
func main() {
number := []int{1, 2, 3, 4, 5}
for _, v := range number {
go tggg1(v)
go tggg(&v)
}
time.Sleep(5*time.Second)
}
```
输出结果:
```
v = 1
p = 0xc000084010, v = 5
v = 2
p = 0xc000084010, v = 5
v = 3
p = 0xc000084010, v = 5
v = 4
p = 0xc000084010, v = 5
v = 5
p = 0xc000084010, v = 5
```
---------------------------------------时间线---------------------------
我有加了个sleep 输出就不一样了,怎么感觉从地址里取值有延时啊
```go
package main
import (
"fmt"
"time"
)
func tggg(p *int) {
fmt.Printf("p = %p, v = %d\n", p, *p)
}
func tggg1(t int) {
fmt.Printf("v = %d\n", t)
}
func main() {
number := []int{1, 2, 3, 4, 5}
for k, v := range number {
// go tggg1(v)
switch k {
case 0:
time.Sleep(1*time.Second)
go tggg(&v)
case 1:
time.Sleep(2*time.Second)
go tggg(&v)
case 2:
time.Sleep(3*time.Second)
go tggg(&v)
case 3:
time.Sleep(4*time.Second)
go tggg(&v)
case 4:
time.Sleep(5*time.Second)
go tggg(&v)
}
// go tggg(&v)
}
time.Sleep(5*time.Second)
}
```
输出结果:
```
= 0xc000084010, v = 2
p = 0xc000084010, v = 3
p = 0xc000084010, v = 4
p = 0xc000084010, v = 5
p = 0xc000084010, v = 5
```
但是为啥没有1 ,却有两个5呢?????
十分感谢 <a href="/user/anko" title="@anko">@anko</a> ,看到你的解答,我终于明白了,我这样理解对不对:是不是根本原因是主协程代码跟子协程代码 谁先执行 是不确定的,结果全是同一个值的,是主协程的for循环都执行完了,子协程比他晚,所以用指针取值,只能取得最后的值
我这样理解对不对???
如果要想让他根据那个本意 1,2,3,4,5显示,是不是需要通过管道来控制
#15
更多评论
啊,我是看了https://studygolang.com/articles/23530#reply1 才知道这个的。。。
我不是很理解啊,虽然传的是指针,但是那个地址存的值不是应该实时变得吗?为啥不变啊
#2