Methods

suggest change

Struct methods are functions attached to structs:

type User struct {
	name string
}

func (u User) Name() string {
	return u.name
}

func (u *User) SetName(newName string) {
	u.name = newName
}

func main() {
	var me User

	me.SetName("Slim Shady")
	fmt.Println("My name is", me.Name())
}
My name is Slim Shady

The only difference is the addition of the method receiver.

It may be declared either as an instance of the type or a pointer to an instance of the type.

Since SetName() mutates the instance, the receiver must be a pointer in order to effect a permanent change in the instance.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents