This is a creation in
Article, where the information may have evolved or changed.
Overview
Many people (especially novices) often ask a question when they write the Go language code, that is, whether a method's recipient type should be a value type or a pointer type, and the Go Wiki has a good explanation for that, and I'll translate it.
When to use value types
- If the recipient is one
map , func or chan the value type is used (because they are reference types in themselves).
- The value type is used if the recipient is one and the
slice method does not perform an reslice operation and does not reallocate memory to it slice .
- If the recipient is a small array or a primitive value type struct type (such as a
time.Time type), and there is no modifiable field and pointer, or if the recipient is a simple primitive type like Yes int string , use the value type as well.
A recipient of a value type can reduce a certain amount of garbage generation, and if a value is passed to the method of a value type recipient, a copy on a stack overrides allocating memory on the heap (but not guaranteed to be successful), so do not select the value type recipient for this reason until you understand what the code wants to do.
When to use pointer types
- If the method needs to modify the recipient, the recipient must be a pointer type.
- If the recipient is a
sync.Mutex struct that contains or is similar to a synchronization field, the recipient must be a pointer so that the copy can be avoided.
- If the recipient is a large struct or array, then the pointer type recipient is more efficient. (How big is it?) Suppose you pass all the elements of the recipient as parameters to the method, and if you think that the parameters are a bit more, then it is large.
- Can the recipient be modified when calling functions and methods concurrently in this method? A recipient of a value type creates a copy when the method is called, so the external modification does not work on the recipient. If the modification must be visible to the original recipient, then the recipient must be a pointer type.
- If the recipient is a struct, an array or
slice any one of them is a pointer type and may be modified, it is recommended to use the pointer type recipient, which increases the readability of the program
Remember to use the pointer recipient when you are still having doubts about what to use and who you are not.
About recipients ' names
Community-agreed recipient names are one or two-letter abbreviations for the type (like c or cl for Client ). Don't use generic names like, me this or self , don't use overly descriptive names, and finally, if you're using one place c , don't use it anywhere else cl .
Reference
http://se77en.cc/2014/05/04/choose-whether-to-use-a-value-or-pointer-receiver-on-methods/