英文:
Overwrite existing value with new value
问题
请看下面的代码片段。
package main
import (
"fmt"
)
type class struct {
prop1 string
prop2 string
}
func main() {
va1 := &class{"Hello", "Foo"}
fmt.Println(&va1)
va1 = &class{"TOO", "Boo"}
fmt.Println(&va1)
}
结果是我得到了相同的指针地址。
0x1215a0c0
0x1215a0c0
使用&T{}
会分配一个新的零值地址。但为什么这里我得到了相同的地址?我只是在第二次赋值时覆盖了值吗?
英文:
Look at the following code snippet.
package main
import (
"fmt"
)
type class struct {
prop1 string
prop2 string
}
func main() {
va1 := &class{"Hello", "Foo"}
fmt.Println(&va1)
va1 = &class{"TOO", "Boo"}
fmt.Println(&va1)
}
As a result I've got the same pointed address.
0x1215a0c0
0x1215a0c0
With &T{} it will allocate new zeroed value address. But why here I've got the same address? Do I just override on second assignment the value?
答案1
得分: 3
该语句
fmt.Println(&va1)
打印的是变量va1
的地址,而不是va1
指向的内容。变量的地址不会改变。
尝试运行以下程序:
va1 := &class{"Hello", "Foo"}
fmt.Printf("&va1: %v, pointer: %p, value: %v\n", &va1, va1, va1)
va2 := va1
va1 = &class{"TOO", "Boo"}
fmt.Printf("&va1: %v, pointer: %p, value: %v\n", &va1, va1, va1)
fmt.Printf("&va2: %v, pointer: %p, value: %v\n", &va2, va2, va2)
该程序输出:
&va1: 0x1030e0c0, pointer: 0x10328000, value: &{Hello Foo}
&va1: 0x1030e0c0, pointer: 0x10328050, value: &{TOO Boo}
&va2: 0x1030e0d0, pointer: 0x10328000, value: &{Hello Foo}
请注意,变量va1
的地址没有改变,但va1
指向的内容发生了变化。此外,将指针赋给va1
并不会修改va1
指向的值。
英文:
The statement
fmt.Println(&va1)
prints the address of the variable va1
, not what va1
is pointing to. The address of the variable does not change.
Try this program:
va1 := &class{"Hello", "Foo"}
fmt.Printf("&va1: %v, pointer: %p, value: %v\n", &va1, va1, va1)
va2 := va1
va1 = &class{"TOO", "Boo"}
fmt.Printf("&va1: %v, pointer: %p, value: %v\n", &va1, va1, va1)
fmt.Printf("&va2: %v, pointer: %p, value: %v\n", &va2, va2, va2)
This program prints:
&va1: 0x1030e0c0, pointer: 0x10328000, value: &{Hello Foo}
&va1: 0x1030e0c0, pointer: 0x10328050, value: &{TOO Boo}
&va2: 0x1030e0d0, pointer: 0x10328000, value: &{Hello Foo}
Note that the address of the variable va1 does not change, but what va1 points to does change. Also, the assignment of a pointer to va1 does not modify the value va1 pointed to.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论