Here's an example of what I mean:
type person struct {
name string
age int
}
func example() *person {
return &person{"Frank", 15}
}
func main() {
frank := example()
fmt.Println(frank.name)
}
So what I mean is why would the function have *person (literal), when you are returning &person (address).
Edit:
Furthermore, when changed to this code:
func example() *person {
p := &person{"Frank", 15}
fmt.Printf("%x\n", p)
fmt.Printf("%v\n", *p)
return p
}
The output is:
&{4672616e6b f}
{Frank 15}
Frank
The pointer being returned CLEARLY does not equal the struct literal when using p, (effectively (&person{"Frank", 15}).
评论:
gtarget:
Franke123:The syntax
*person
means a pointer to aperson
. When you return&person{"Frank", 15}
you are saying return the address of the structperson
you just created. A pointer is really just a variable holding the address of something else.
dmikalova:Got it! That makes sense now :) Thank you.
DualRearWheels:Thanks, that cleared things up for me too.
Franke123:Quick tip: why would anyone use pointers anyway? 2 reasons:
You can change struct using pointer from any place (loops, other functions etc.)
Performance difference can be huge compared to not using pointer. With pointer program only copies address (4 or 8 bytes depending on your architecture). With struct as value program must copy much more (sum of all sizes of all fields, this can go to 100+ bytes depending on fields).
Thanks! As a pretty new programmer who learned JS first, pointers can be kind of confusing! But I do see the advantages.
