Go – Methods and Interfaces

Methods

GO has no Classes. However, it has Methods that can be defined on ‘types’. A Method is a function with a special ‘receiver’ argument. In the example below, ‘v‘ is the receiver of the type ‘Square‘, to the method ‘Sqroot‘.

A Method can only be declared on a type which is present in the same package as the method.

Pointer Receivers

A method can also be declared with the receiver being a Pointer. A Pointer receiver is very commonly used, as it can modify the underlying value of the type.

There can be two reasons to choose a pointer receiver instead of a value. First is to modify the underlying value and second to avoid copying the value on each method call. If the receiver is large, pointer receiver can prove to be more efficient.