Go Methods
A method is a function joined to a type. A method is called on a value of that type with a dot.
A Value Receiver
Describe is joined to the Person type. It reads the fields of its receiver.
package main
import "fmt"
type Person struct {
Name string
Age int
}
func (p Person) Describe() {
fmt.Println(p.Name, "is", p.Age)
}
func main() {
person := Person{Name: "Hana", Age: 27}
person.Describe()
}A Pointer Receiver
Birthday takes a *Person receiver. The age it raises is the age of the original person.
package main
import "fmt"
type Person struct {
Name string
Age int
}
func (p *Person) Birthday() {
p.Age++
}
func main() {
person := Person{Name: "Hana", Age: 27}
person.Birthday()
fmt.Println(person.Age)
}Methods That Return Values
Area and Perimeter both read the Rectangle receiver. Each one returns a number.
package main
import "fmt"
type Rectangle struct {
Width int
Height int
}
func (r Rectangle) Area() int {
return r.Width * r.Height
}
func (r Rectangle) Perimeter() int {
return 2 * (r.Width + r.Height)
}
func main() {
rect := Rectangle{Width: 3, Height: 4}
fmt.Println(rect.Area())
fmt.Println(rect.Perimeter())
}Example
package main
import "fmt"
type Counter struct {
Count int
}
func (c *Counter) Inc() {
c.Count++
}
func (c Counter) Value() int {
return c.Count
}
func main() {
counter := Counter{}
counter.Inc()
counter.Inc()
counter.Inc()
fmt.Println(counter.Value())
}Key points
- Method: a function joined to a type.
- The receiver sits in parentheses before the method name.
- A value receiver works on a copy of the value.
- A pointer receiver works on the original value, so its changes stay.
- Call a method with the value, a dot, and the method name.
- A method can take parameters and return values like a function.
In this example, the Counter struct holds one Count field. Inc uses a pointer receiver, so each call raises the count of the same counter. Value uses a value receiver and returns the count. Three Inc calls make Value return 3.
Note
Methods are declared outside the struct, not inside its braces.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Go Playground
Exercise
A method must change a field of the original struct. Which receiver does it need?