我還在學習中,需要一隻手來清理我的頭。指針新手 - 更正我
以下程序輸出Power
值爲1
每個Println
。我期待1
作爲第一個輸出和2
作爲第二個輸出。 我的假設是Change
func
用new address
覆蓋address of
s
,並且此更改將反映回調用方(main func
)。在這種情況下,當它調用第二個Println
時,原始地址將指向新創建的地址。 我的假設是錯誤的,但我不明白爲什麼。
package main
import (
"fmt"
)
type Pod struct{
Power int
}
func main() {
pod := &Pod{1}
fmt.Println(pod.Power)
Change(pod)
fmt.Println(pod.Power)
}
func Change(s *Pod) {
s = &Pod{2}
}
要在掩護下會發生什麼進一步探索,我也試圖打印地址,這時候,它看起來像下面;
import (
"fmt"
)
type Pod struct{
Power int
}
func main() {
pod := &Pod{ 1}
fmt.Println(&pod) //0xc04202c020
Change(pod)
fmt.Println(&pod) //0xc04202c020
}
func Change(s *Pod) {
fmt.Println(&s) //0xc04202c030 (I was expecting 0xc04202c020 here)
s = &Pod{ 2}
fmt.Println(&s) //0xc04202c030
}
謝謝你,很好解釋。 – Nair
@Nair我看到你以前的評論現在已經消失了,但正因爲如此,我編輯了答案以提供更多信息。我希望能幫到你:) –
是的。那與我忘記了一會兒的時間,現在回想起我在大學裏學到的東西有關。一段時間以來,我們一直在用所有新的gen語言去指針。不理我。 – Nair