简体   繁体   English

访问结构字段时Golang结构文字和指针之间的区别

[英]Difference between Golang struct literals & pointers when accessing struct fields

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. 他们不是我想知道的。

u is a variable of type Person . uPerson类型的变量。 p is a variable of type "pointer to Person ", and it is initialized with the address of an anonymous ("temporary") object. p是类型为“指向Person指针”的变量,并使用匿名(“临时”)对象的地址初始化。 The expression p.Name uses auto-dereferencing of pointers and is equivalent to (*p).Name . 表达式p.Name使用指针的自动引用,并且等效于(*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. p指向的对象只要p指向它,它就会被Go的不确定性内存管理器销毁。

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. p.Nameu.Name都是string类型的string ,并且它们没有“被指针传递”,因为它们的地址没有被调用。 In the case of fmt.Println , the value is actually passed "by interface" using Go's structural subtyping form of ad-hoc polymorphism. 对于fmt.Println ,该值实际上是使用Go的即席多态性的结构子类型形式“通过接口”传递的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM