5

Pointer vs. value receiver

 3 years ago
source link: https://yourbasic.org/golang/pointer-vs-value-receiver/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Pointer vs. value receiver

yourbasic.org/golang
pointing-man.jpg

Basic guidelines

  • For a given type, don’t mix value and pointer receivers.
  • If in doubt, use pointer receivers (they are safe and extendable).

Pointer receivers

You must use pointer receivers

  • if any method needs to mutate the receiver,
  • for structs that contain a sync.Mutex or similar synchronizing field (they musn’t be copied).

You probably want to use pointer receivers

  • for large structs or arrays (it can be more efficient),
  • in all other cases.

Value receivers

You probably want to use value receivers

  • for map, func and chan types,
  • for simple basic types such as int or string,
  • for small arrays or structs that are value types, with no mutable fields and no pointers.

You may want to use value receivers

  • for slices with methods that do not reslice or reallocate the slice.

Share:             


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK