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.

main.go
type user struct {
name string
}
func sayHello(u user) {
fmt.Printf("Hello, %s from function \n", u.name)
}
func (u user) sayHello() {
fmt.Printf("Hello, %s from method\n", u.name)
}
func main() {
u := user{
name: "Gopher",
}
// function call
sayHello(u)
// method call
u.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.

main.go
func (u *user) updateUser() {
u.name = "Bob"
}
func main() {
u := &user{
name: "Gopher",
}
u.updateUser()
fmt.Println(u.name)
}