HowtoGo
Home / Functions / Methods and Receivers
Functions

Methods and Receivers

A method is a function with a receiver argument, written between func and the method name. The receiver binds the function to a type, so it can be called with dot notation.

A value receiver, (p Person), gives the method its own copy of the struct. Greet only reads fields, so a copy is fine.

type Person struct {
    Name string
    Age  int
}

func (p Person) Greet() string {
    return "Hi, I'm " + p.Name
}

Calling a method looks the same as accessing a field: p.Greet(). Go resolves the method by matching p's type against the receiver.

p := Person{Name: "Ana", Age: 30}
fmt.Println(p.Greet())

A pointer receiver, (p *Person), gives the method access to the original struct instead of a copy. Use it whenever the method needs to mutate a field.

func (p *Person) Birthday() {
    p.Age++
}

A pointer-receiver method automatically takes the address of p, so p.Birthday() works without writing (&p).Birthday().

p.Birthday()
fmt.Println(p.Age)

31 confirms Birthday mutated the original p, not a copy. A value-receiver method could not have changed Age.

Terminal
$ go run receivers.go
Hi, I'm Ana
31