Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Reference method vs Value method in Go

Developers often get confused while defining methods on struct type, whether to consider the receiver s as value type i.e MyStruct or reference type *MyStruct.

func (s *MyStruct) pointerMethod() { } // method on pointer

func (s MyStruct)  valueMethod()   { } // method on value


Reference Type
If the method expects to do a mutation to object, i.e method is going to modify the value of one of the existing properties. Then reference type needs to be used.


Value Type
If the method expects to do a non mutation to object, i.e read a property and compute on the property without making modification. In this approach, Go copies the object and passes to method.