我不明白為什么在為另一個對象分配指針時,指針接收器不會更新。下面是一個示例:獲取是導出的獲取器,獲取未導出,我希望 Get() 返回一個指向對象的指針,該指針包含在由字符串索引的指針映射中。我不明白為什么get()方法的指針接收器沒有更新。我每次都嘗試了不同的策略,結果幾乎相同:取消引用,在變量聲明中使用&而不是*...去游樂場在這里: https://play.golang.org/p/zCLLvucbMjy有什么想法嗎?謝謝!package mainimport ( "fmt")type MyCollection map[string]*MyTypetype MyType struct { int}var collection MyCollectionfunc Get(key string) *MyType { var rslt *MyType // rslt := &MyType{}: gives almost the same result rslt.get(key) fmt.Println("rslt:", rslt) // Should print "rslt: &{2}" return rslt}func (m *MyType) get(key string) { m = collection[key] // *m = collection[key] : cannot use collection[key] (type *MyType) as type MyType in assignment fmt.Println("get m:", m) // Should print "get m: &{2}"}func main() { collection = make(map[string]*MyType) collection["1"] = &MyType{1} collection["2"] = &MyType{2} m := &MyType{1} m = Get("2") fmt.Println("final m", m) // Should print "final m: &{2}"}
1 回答

婷婷同學_
TA貢獻1844條經驗 獲得超8個贊
您需要取消引用接收方,并從映射中為其分配取消引用值,即 。*m = *collection[key]
確保在調用變量之前已初始化,而不是 ,例如 。rslt.getrsltnilrslt := &MyType{}
func Get(key string) *MyType {
rslt := &MyType{}
rslt.get(key)
fmt.Println("rslt:", rslt) // Should print "rslt: &{2}"
return rslt
}
func (m *MyType) get(key string) {
*m = *collection[key]
fmt.Println("get m:", m) // Should print "get m: &{2}"
}
https://play.golang.org/p/zhsC9PR3kwc
請注意,原因還不夠,因為接收方始終是調用方變量的副本。直接分配給接收方只會更新該副本,而不會更改調用方的變量。若要更新接收方和調用方的變量都指向的數據,必須取消引用變量。請注意,每個調用都有自己的副本。m = collection[key]
https://play.golang.org/p/um3JLjzSPrD
- 1 回答
- 0 關注
- 100 瀏覽
添加回答
舉報
0/150
提交
取消