In Go there are various ways to return a struct
value or slice thereof. For individual ones I\'ve seen:
type MyStruct struct {
Val int
}
fu
Three main reasons when you would want to use method receivers as pointers:
"First, and most important, does the method need to modify the receiver? If it does, the receiver must be a pointer."
"Second is the consideration of efficiency. If the receiver is large, a big struct for instance, it will be much cheaper to use a pointer receiver."
"Next is consistency. If some of the methods of the type must have pointer receivers, the rest should too, so the method set is consistent regardless of how the type is used"
Reference : https://golang.org/doc/faq#methods_on_values_or_pointers
Edit : Another important thing is to know the actual "type" that you are sending to function. The type can either be a 'value type' or 'reference type'.
Even as slices and maps acts as references, we might want to pass them as pointers in scenarios like changing the length of the slice in the function.
A case where you generally need to return a pointer is when constructing an instance of some stateful or shareable resource. This is often done by functions prefixed with New.
Because they represent a specific instance of something and they may need to coordinate some activity, it doesn't make a lot of sense to generate duplicated/copied structures representing the same resource -- so the returned pointer acts as the handle to the resource itself.
Some examples:
In other cases, pointers are returned just because the structure may be too large to copy by default:
Alternatively, returning pointers directly could be avoided by instead returning a copy of a structure that contains the pointer internally, but maybe this isn't considered idiomatic:
If you can (e.g. a non-shared resource that does not need to be passed as reference), use a value. By the following reasons:
Reason 1: you will allocate less items in the stack. Allocating/deallocating from stack is immediate, but allocating/deallocating on Heap may be very expensive (allocation time + garbage collection). You can see some basic numbers here: http://www.macias.info/entry/201802102230_go_values_vs_references.md
Reason 2: especially if you store returned values in slices, your memory objects will be more compacted in memory: looping a slice where all the items are contiguous is much faster than iterating a slice where all the items are pointers to other parts of the memory. Not for the indirection step but for the increase of cache misses.
Myth breaker: a typical x86 cache line are 64 bytes. Most structs are smaller than that. The time of copying a cache line in memory is similar to copying a pointer.
Only if a critical part of your code is slow I would try some micro-optimization and check if using pointers improves somewhat the speed, at the cost of less readability and mantainability.
tl;dr:
One case where you should often use a pointer:
Some situations where you don't need pointers:
Code review guidelines suggest passing small structs like type Point struct { latitude, longitude float64 }
, and maybe even things a bit bigger, as values, unless the function you're calling needs to be able to modify them in place.
bytes.Replace
takes 10 words' worth of args (three slices and an int
). You can find situations where copying even large structs turns out a performance win, but the rule of thumb is not to.For slices, you don't need to pass a pointer to change elements of the array. io.Reader.Read(p []byte)
changes the bytes of p
, for instance. It's arguably a special case of "treat little structs like values," since internally you're passing around a little structure called a slice header (see Russ Cox (rsc)'s explanation). Similarly, you don't need a pointer to modify a map or communicate on a channel.
For slices you'll reslice (change the start/length/capacity of), built-in functions like append
accept a slice value and return a new one. I'd imitate that; it avoids aliasing, returning a new slice helps call attention to the fact that a new array might be allocated, and it's familiar to callers.
interface{}
parameter.Maps, channels, strings, and function and interface values, like slices, are internally references or structures that contain references already, so if you're just trying to avoid getting the underlying data copied, you don't need to pass pointers to them. (rsc wrote a separate post on how interface values are stored).
*string
for that reason, for example.Where you use pointers:
Consider whether your function should be a method on whichever struct you need a pointer to. People expect a lot of methods on x
to modify x
, so making the modified struct the receiver may help to minimize surprise. There are guidelines on when receivers should be pointers.
Functions that have effects on their non-receiver params should make that clear in the godoc, or better yet, the godoc and the name (like reader.WriteTo(writer)
).
You mention accepting a pointer to avoid allocations by allowing reuse; changing APIs for the sake of memory reuse is an optimization I'd delay until it's clear the allocations have a nontrivial cost, and then I'd look for a way that doesn't force the trickier API on all users:
Reset()
method to put an object back in a blank state, like some stdlib types offer. Users who don't care or can't save an allocation don't have to call it.existingUser.LoadFromJSON(json []byte) error
could be wrapped by NewUserFromJSON(json []byte) (*User, error)
. Again, it pushes the choice between laziness and pinching allocations to the individual caller.sync.Pool
can help. (CloudFlare published a useful (pre-sync.Pool) blog post about recycling.)Finally, on whether your slices should be of pointers: slices of values can be useful, and save you allocations and cache misses. There can be blockers:
NewFoo() *Foo
rather than let Go initialize with the zero value.append
copies items when it grows the underlying array. Pointers you got before the append
point to the wrong place after, copying can be slower for huge structs, and for e.g. sync.Mutex
copying isn't allowed. Insert/delete in the middle and sorting similarly move items around.Broadly, value slices can make sense if either you get all of your items in place up front and don't move them (e.g., no more append
s after initial setup), or if you do keep moving them around but you're sure that's OK (no/careful use of pointers to items, items are small enough to copy efficiently, etc.). Sometimes you have to think about or measure the specifics of your situation, but that's a rough guide.