Best Practice: Pointer or Value Receiver?

Common difficulties in defining structural methods.

Especially when determining the receiver of a method, should you use a pointer receiver or a value receiver?

func (t *Type) Method() {} //pointer receiver

versus

func (t Type) Method() {} //value receiver

Method receivers can be similar in behavior to function arguments, and everything that applies to passing pointers or values as function arguments still applies to method receivers.

When should you use pointer receivers

Modify recipient

If you want to change the receiver state in the method, manipulate its value,Use pointer receiver. For value receivers that are copied by value, this is not possible. Any modification to the value receiver is the local content of the copy.

optimization

If the structure on which the method is to be defined is large, copying it is much more expensive than using a value receiver.

The value receiver operates on a copy of the original type value. This means paying a certain price, especially when the structure is very large and pointer reception is more efficient.

When value receivers are better

If you don’t need to edit the receiver value,Use value receiver.

The value receiver is concurrently safe, whilePointer receivers are not concurrently safe.

When should we weigh

In some cases, you may want to use pointer receivers for methods that normally use value receivers, and when you define other pointer receivers on that type,consistencyYou should use pointer receivers in all methods.

read more


More tutorials: