27. Methods
Functions on type
Methods
In Go, methods are functions which are attached to a particular type. This gives functionality similar to Object Oriented Programming. Since methods are attached to particular type, we can reuse method name to attach them to different types.
Declaring Methods
Method declaration is similar to function declaration, but in addition we need to provide the type to which this method is attached to. This type is called receiver.
func (receiver type) name() { code to execute}
First declaration below is a function sayHello
, while second declaration is method sayHello.
Pointer Receiver
We use pointer to share data to avoid unnecessary copy operation on data. Similarly, pointer receivers are used so that method can operate directly operate on data without making copy operation. We are passing pointer to user and updateUser
method updates the same value. that we have created in main
function.
Last updated