Per the Go tour page 28 and page 53
They show a variable that is a pointer to a struct literal. Why is this not the default behavior? I’m unfamiliar with C, so it’s hard to wrap my head around it. The only time I can see when it might not be more beneficial to use a pointer is when the struct literal is unique, and won’t be in use for the rest program and so you would want it to be garbage collected as soon as possible. I’m not even sure if a modern language like Go even works that way.
My question is this. When should I assign a pointer to a struct literal to a variable, and when should I assign the struct literal itself?
Thanks.
Using a pointer instead of just a struct literal is helpful when
In other cases, it’s fine to simply use the struct literal. For a small struct, you can think about the question just as using an
intor an*int: most of the times the int is fine but sometimes you pass a pointer so that the receiver can modify your int variable.In the Go tour exercises you link to, the Vertex struct is small and has about the same semantic than any number. In my opinion it would have been fine to use it as struct directly and to define the
Scaledfunction in #53 like this :because having
would create a new vertex just like
creates a new
float.This is similar to how is handled the standard
Timestruct (defined here), which is usually kept in variables of typeTimeand not*Time.But there is no definite rule and, depending on the use, I could very well have kept both
ScaleandScaled.