为什么在结构体上使用“&”运算符不返回数字地址?

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

Why the & operator on struct doesn't return a digital address?

问题

我刚开始学习 Golang。

我发现 & 运算符在简单类型和结构体中的行为不同。

  • 对于简单类型,& 返回一个地址。

  • 对于结构体,它返回其他内容。

代码:

package main

import "fmt"

type person struct {
    name string
    age  int
}

func main() {
    s1 := "abc"
    fmt.Println("s1 address =", &s1)

    s2 := person{"Sam", 55}
    fmt.Println("s2 address =", &s2)
}

输出:

[ `hello` | done: 79.0079ms ]
    s1 address = 0xc04203c1e0
    s2 address = &{Sam 55}   <======== 这是什么?为什么不是像上面那样的地址?

再次强调,这个设计是“必须的”还是“偶然的”?

英文:

I just started to learn the golang.

I found the &amp; operator behaves differently for simple type and struct.

  • For simple type, &amp; returns an address.

  • For struct, it returns something else.

Code:

package main

import &quot;fmt&quot;

type person struct {
	name string
	age  int
}

func main() {
	s1 := &quot;abc&quot;
	fmt.Println(&quot;s1 address =&quot;, &amp;s1)

	s2 := person{&quot;Sam&quot;, 55}
	fmt.Println(&quot;s2 address = &quot;, &amp;s2)

}

Output:

[ `hello` | done: 79.0079ms ]
	s1 address = 0xc04203c1e0
	s2 address =  &amp;{Sam 55}   &lt;======== What&#39;s this? And why not some address like above?

Again, is this design a have-to or a happen-to?

答案1

得分: 10

&amp; 单元操作符在内置类型和结构体中的行为相同,它用于获取变量的内存地址。在这个例子中,我们会看到 &amp;{Sam 55},因为Go语言默认会检查 fmt.Println() 中的参数是结构体还是指向结构体的指针,并在这种情况下尝试打印结构体的每个字段以进行调试。但是,如果你想要看到一个指针,你可以使用 fmt.Printf() 和 %p,像这样:

func main() {
    s1 := "abc"
    fmt.Println("s1 address =", &s1)

    s2 := person{"Sam", 55}

    fmt.Println("s2 as pointer =", &s2)

    fmt.Printf("s2 address = %p value with fields %+v", &s2, s2)
}

额外提示:你可以使用 %+v 来打印字段名和值。

链接:https://play.golang.org/p/p7OVRu8YWB

英文:

The unitary operator &amp; behaves the same for builtin types and structs, it's used to get the memory address of a var. In this case we'll see &amp;{Sam 55} because Go always checks by default if the parameter in fmt.Println() is a struct or a pointer to struct and in that case will try to print each field of the struct for debugging purposes, but if you want to see a pointer you can use fmt.Printf() with %p, like this:

func main() {
	s1 := &quot;abc&quot;
	fmt.Println(&quot;s1 address =&quot;, &amp;s1)

	s2 := person{&quot;Sam&quot;, 55}
	
	fmt.Println(&quot;s2 as pointer =&quot;, &amp;s2)
	
	fmt.Printf(&quot;s2 address = %p value with fields %+v&quot;, &amp;s2, s2)
}

Bonus: you can use %+v to print field names and values

https://play.golang.org/p/p7OVRu8YWB

huangapple
  • 本文由 发表于 2016年11月20日 17:19:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/40702421.html
匿名

发表评论

匿名网友

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

确定