简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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