Is the Go language's method recipient type a value type or a pointer type?

  • 2020-05-10 18:21:11
  • OfStack

An overview of the

One question that many people (especially beginners) often ask when writing Go code is whether the receiver type of a method should be a value type or a pointer type. This is well explained in wiki of Go.

When to use a value type

1. If the receiver is an map, func, or chan, use the value type (because they are reference types themselves).
2. If the receiver is an slice and the method does not perform the reslice operation or reallocate memory to slice, use the value type.
3. If the receiver is a small array or a native value type struct type (such as time.Time) and there are no modifiers for fields and Pointers, or if the receiver is a simple base type like int and string, use the value type.

A value type of the receiver can be reduced by 1 number of waste generated, if a value is introduced to a receiver, the method of value type 1 copy on the stack will replace the memory allocated on the heap (but not guarantee success) 1, so before you want to do not understand the code, don't choose value type for this reason the recipient.

When to use pointer types

1. If the method needs to modify the receiver, the receiver must be of pointer type.
2. If the receiver is a struct containing sync.Mutex or similar synchronous fields, the receiver must be a pointer to avoid copying.
3. If the receiver is a large struct or array, the pointer type receiver is more efficient. How big is too big? Assume that all the elements of the receiver are passed to the method as parameters. If you think the parameters are too many, then it is large.
4. When concurrent functions and methods are called from this method, can the recipient be modified? The recipient of a value type creates a copy when the method is called, so external modifications cannot be applied to the recipient. If the modification must be visible to the original recipient, the recipient must be of pointer type.
5. If the receiver is a struct, array, or slice, and any one of them is a pointer type and may be modified, it is recommended to use the pointer type receiver, which will increase the readability of the program

When you finish reading this and still have doubts about which recipient to use, remember to use pointer recipients.

The name of the recipient

The recipient name of the community convention is a one - or two-letter abbreviation of the type (like c or cl for Client). Don't use generic names like me, this, or self, and don't use overly descriptive names. Finally, if you use c in one place, don't use cl elsewhere.


Related articles: