英文:
Difference between Golang struct literals & pointers when accessing struct fields
问题
我不理解结构体字面量和结构体指针在访问结构体字段时的区别。它们在内部行为上有什么不同吗?
type Person struct {
Name string
}
p := &Person{Name: "Alice"}
u := Person{Name: "Bob"}
fmt.Println(p.Name) // 有什么区别吗?
fmt.Println(u.Name) // 有什么区别吗?
我搜索了一下,但是我找到的帖子都是解释值和指针之间的区别,或者是将值传递给方法与将指针传递给方法的区别。它们不是我想要了解的内容。
英文:
I don't understand the difference between a struct literal and a struct pointer when accessing struct fields. Is there any different internal behavior ?
type Person struct {
Name string
}
p := &Person{Name: "Alice"}
u := Person{Name: "Bob"}
fmt.Println(p.Name) // any difference ?
fmt.Println(u.Name) // any difference ?
I searched for this but posts I found all explain about difference between value & pointer, or "passing a value" vs "passing a pointer" to a method. They are not what I want to know.
答案1
得分: 11
u
是一个类型为Person
的变量。p
是一个类型为"指向Person
的指针"的变量,并且它被初始化为一个匿名("临时")对象的地址。表达式p.Name
使用指针的自动解引用,等同于(*p).Name
。p
指向的对象的生命周期与p
指向它的时间一样长,并且可能会被Go的非确定性内存管理器在此之后销毁。
p.Name
和u.Name
都是类型为string
的表达式,并且它们不是"通过指针传递",因为在调用中没有取得它们的地址。在fmt.Println
的情况下,实际上是通过Go的结构子类型化形式的特殊多态性"通过接口"传递值的。
英文:
u
is a variable of type Person
. p
is a variable of type "pointer to Person
", and it is initialized with the address of an anonymous ("temporary") object. The expression p.Name
uses auto-dereferencing of pointers and is equivalent to (*p).Name
. The object that p
points to lives as long as p
points to it and may thereafter be destroyed by Go's non-deterministic memory manager.
Both p.Name
and u.Name
are expressions of type string
, and they're not "passed by pointer" since their address is not taken in the call. In the case of fmt.Println
, the value is actually passed "by interface" using Go's structural subtyping form of ad-hoc polymorphism.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论