Golang中结构体字面量和指针在访问结构体字段时的区别是什么?

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

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).Namep指向的对象的生命周期与p指向它的时间一样长,并且可能会被Go的非确定性内存管理器在此之后销毁。

p.Nameu.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.

huangapple
  • 本文由 发表于 2015年12月29日 09:43:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/34503284.html
匿名

发表评论

匿名网友

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

确定