package main
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
func changePoint(count *int) {
defer wg.Done()
nowVal := 7
//这种情况在main函数中count指向的值不会更新
//count = &nowVal
//这种情况在main函数中count指向的值会更新
*count = nowVal
}
func ExampleGoroutine(orgId string) {
initVal := 5
count := &initVal
wg.Add(1)
go changePoint(count)
wg.Wait()
fmt.Println(*count)
}
func main() {
ExampleGoroutine("test")
}
碰巧遇到这个问题。changePoint 函数传入的指针是值拷贝,所以入参count的作用域只在changePoint函数内。
需要修改count指向对象的值的话,需要直接对其指向的地址进行赋值,而不是把新值的地址赋给它
网友评论