Go Tutorial · Functions and Methods · Lesson 19 of 30

Go Methods

Attach methods to types with value and pointer receivers.

Methods

A method is a function with a receiver — the type it belongs to:

Example 1
package main

import "fmt"

type Rect struct {
	Width, Height float64
}

func (r Rect) Area() float64 { return r.Width * r.Height }

func (r Rect) Perimeter() float64 { return 2 * (r.Width + r.Height) }

func (r *Rect) Scale(f float64) { // pointer receiver: modifies r
	r.Width *= f
	r.Height *= f
}

func (r Rect) String() string { // satisfies fmt.Stringer
	return fmt.Sprintf("Rect(%gx%g)", r.Width, r.Height)
}

func main() {
	r := Rect{Width: 3, Height: 4}
	fmt.Println(r.Area(), r.Perimeter())
	r.Scale(2)
	fmt.Println(r.Width, r.Height, r.Area())
	fmt.Println(r)
}

Output

12 14
6 8 48
Rect(6x8)

Run this on your computer — see “Get Started” for setup.

Value vs pointer receivers

  • Value receiver (r Rect) — works on a copy; can't change the original.
  • Pointer receiver (r *Rect) — can modify the value, and avoids copying large structs.

If any method needs a pointer receiver, make all of the type's methods pointer receivers for consistency. Go automatically takes the address when you call a pointer method on an addressable value.

Test yourself

Which receiver type lets a method modify the original struct?

  1. A value receiver
  2. A pointer receiver
  3. Any receiver
  4. Methods can't modify structs
Show answer

Answer: A pointer receiver