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.
Pointers are helpful because you can "move them around" more easily. Instead of having to copy over the whole stucture each time, you can just leave it where it is in memory and instead pass a pointer to it around.
Avoid using pointers if concurrency safety is required. Keep in mind that it is an intrusive way to modify variables using pointers, and sometimes data safety is first priority. Try not to nest pointers like **string , which will make your code extremely complex, although it is allowed by Go.
The struct types store the variables of different data types and we use the struct variable to access the members of the struct. In Go, we can also create a pointer variable of the struct type.
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 int
or 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 Scaled
function in #53 like this :
func (v Vertex) Scaled(f float64) Vertex {
v.X = v.X * f
v.Y = v.Y * f
return v
}
because having
v2 := v1.Scaled(5)
would create a new vertex just like
var f2 float32 = f1 * 5
creates a new float
.
This is similar to how is handled the standard Time
struct (defined here), which is usually kept in variables of type Time
and not *Time
.
But there is no definite rule and, depending on the use, I could very well have kept both Scale
and Scaled
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With