覆盖现有值与新值。

huangapple go评论83阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2014年9月12日 22:38:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/25810825.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定