英文:
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 &
operator behaves differently for simple type and struct.
-
For simple type,
&
returns an address. -
For struct, it returns something else.
Code:
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)
}
Output:
[ `hello` | done: 79.0079ms ]
s1 address = 0xc04203c1e0
s2 address = &{Sam 55} <======== What's this? And why not some address like above?
Again, is this design a have-to
or a happen-to
?
答案1
得分: 10
&
单元操作符在内置类型和结构体中的行为相同,它用于获取变量的内存地址。在这个例子中,我们会看到 &{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 &
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 &{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 := "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)
}
Bonus: you can use %+v
to print field names and values
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论