我的理解是,當我創建一個對象時,foo := &bar{}我正在為該對象分配新內存。那么,當我嘗試在 goroutine 中替換 *foo 時,為什么它沒有獲得新的指針地址?package mainimport ( "fmt" "math/rand" "sync" "time")type pointerToObjects struct { objs *objects}type objects struct { sliceOfObject []*object}type object struct { number int boolean bool}func main() { p := &pointerToObjects{objs: newObjects()} mu := &sync.Mutex{} for _, o := range p.objs.sliceOfObject { o.setBool(true) } // goroutine 1 go func() { ticker := time.NewTicker(time.Second) defer ticker.Stop() for range ticker.C { mu.Lock() fmt.Printf("objects pointer: %v\n", &p.objs) for i, o := range p.objs.sliceOfObject { fmt.Printf("i: %d p: %v n: %d b: %t\n", i, &o, o.number, o.boolean) } fmt.Print("---\n") mu.Unlock() } }() // goroutine 2 go func() { ticker := time.NewTicker(time.Second * 2) defer ticker.Stop() for range ticker.C { newObjects := &objects{sliceOfObject: newSliceOfObject()} mu.Lock() p.objs = newObjects mu.Unlock() fmt.Printf("replaced: %v <-- %v \n", &p.objs, &newObjects) } }() // let the goroutines run for 10 seconds time.Sleep(time.Second * 10)}func newObjects() *objects { objs := &objects{} objs.sliceOfObject = newSliceOfObject() return objs}func newSliceOfObject() []*object { var sliceObjs []*object for i := 0; i < 3; i++ { sliceObjs = append(sliceObjs, newObject()) } return sliceObjs}func newObject() *object { return &object{number: rand.Int()}}func (obj *object) setBool(b bool) { obj.boolean = b}運行時,值會按我的預期更新,但指向的指針p保持objects不變。我希望它會在我打電話時更新*p.objs = *newObjects這是編譯器的把戲嗎?如何獲取“對象指針”以更新到新位置?我需要使用更明確的指針嗎?編輯:修復了比賽條件并嘗試分配p.objs = newObjects但沒有成功。
為什么這個golang指針地址在goroutine中替換時不會改變?
慕無忌1623718
2022-06-06 16:49:26