Methods, value and pointer receivers

A method is a function with a receiver: one extra parameter written before the name, which becomes the value the body calls self without the ceremony. The receiver is either the type or a pointer to it, and that choice decides whether the method changes the caller's value. Methods are attached to a named type, not to a struct only, which is how the standard library gives time.Duration a String and net.IP a String.

Two kinds of receiver

A value receiver gets a copy, exactly as a function argument does, so a write to a field inside the method changes the copy and is lost. A pointer receiver gets the address, so a write reaches the caller. The convention is pointer receivers when any method changes the value, and one kind of receiver for all methods of a type, so that the type has a single method set.

package main import "fmt" type counter struct { n int } func (c counter) Value() int { return c.n } func (c *counter) Inc() { c.n++ } func main() { c := counter{} c.Inc() c.Inc() fmt.Println("pointer receiver changed it:", c.Value()) var copyOf counter = c copyOf.Inc() fmt.Println("original:", c.Value(), "copy:", copyOf.Value()) }

go run receiver.go

pointer receiver changed it: 2
original: 2 copy: 3

The first two calls changed the value through the pointer receiver. The copy was then made from the updated value, and its own Inc moved only the copy, so the two prints differ. A value receiver is right for a small immutable value, a method that only reads, and a type that is compared by value.

The compiler takes the address when it can

A method with a pointer receiver can be called on an addressable value: the compiler inserts the & and calls the method on the address. That is why c.Inc() works on a local variable without &c. A value that is not addressable, such as a map element or a function result, has no address to take, and then the call is a compile error.

package main import "fmt" type counter struct { n int } func (c *counter) Inc() { c.n++ } func main() { c := counter{} c.Inc() ptr := &c ptr.Inc() fmt.Println("through the address:", c.n) counters := map[string]counter{"a": {}} _ = counters }

go run address.go

through the address: 2

Both calls reached the same struct: the local value and the pointer to it name one counter. The map below kept a zero counter and is only there to show the type the next block fails on; a map element is not addressable, so a pointer method cannot be called on it.

Methods on a named type

Any named type can have methods, including one whose underlying type is a number or a string. String() string is special: fmt calls it for %v and %s, so a type gets a readable printout written in Go instead of a formatter elsewhere. A named type keeps its own method set, which is why Celsius(36.6) has Fahrenheit and a plain float64 does not.

package main import "fmt" type Celsius float64 func (c Celsius) Fahrenheit() float64 { return float64(c)*9/5 + 32 } func (c Celsius) String() string { return fmt.Sprintf("%.1f°C", float64(c)) } type Weekday int const ( Sunday Weekday = iota Monday Tuesday ) func (d Weekday) String() string { return [...]string{"Sunday", "Monday", "Tuesday"}[d] } func main() { temp := Celsius(36.6) fmt.Println(temp, temp.Fahrenheit()) fmt.Printf("%v %d %s\n", temp, Monday, Tuesday) }

go run named.go

36.6°C 97.88000000000001
36.6°C 1 Tuesday

36.6°C 97.9 came from the two Celsius methods, and the weekday printed its name because %d asked for the number while the value itself has a String. Go has no method overloading, so a type has one String and one constructor name per package; that is why the standard library uses package-level functions such as time.Parse for the second way to build a value.

The call that cannot be made

A map element is not addressable, because the table can move its entries. A pointer method needs an address, so the compiler refuses the call instead of silently working on a copy that would be thrown away. The message names the method and the type, and the fix is to read the element, call the method on the copy, and store the result back, or to keep pointers in the map.

package main import "fmt" type counter struct { n int } func (c *counter) Inc() { c.n++ } func (c counter) Value() int { return c.n } func main() { counters := map[string]counter{"a": {}} counters["a"].Inc() fmt.Println(counters["a"].Value()) }

go build -o mapcall mapcall.go

# command-line-arguments
./mapcall.go:19:16: cannot call pointer method Inc on counter

The same rule explains why m[k].Field = v failed in the map internals lesson: an address is what a write needs, and an element of a moving table has none. A map of *counter solves it, because the pointer is the element and the struct stays where it was allocated.

Exercises

  1. Give a stack type a Push and a Pop method, and say which receiver kind each needs and why.
  2. Write a Duration named type of int64 milliseconds with a String method that prints 1.5s for 1500. What does fmt.Println(d) print without the method?
  3. Store counters in a map and call a pointer method on one entry. Write the three lines the compiler asks for, then the version with a map of pointers.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does a value receiver receive?

    Answer

    A copy of the value

    The receiver is an ordinary parameter, so a value receiver gets a copy, like any argument.

  2. What does this program print? package main import "fmt" type counter struct { n int } func (c counter) Value() int { return c.n } func (c *counter) Inc() { c.n++ } func main() { c := counter{} c.Inc() c.Inc() fmt.Println("pointer receiver changed it:", c.Value()) var copyOf counter = c copyOf.Inc() fmt.Println("original:", c.Value(), "copy:", copyOf.Value()) }

    Answer

    pointer receiver changed it: 2 / original: 2 copy: 3

    Inc has a pointer receiver, and copyOf was made after the two calls, so its own Inc moved only the copy.

  3. When can a pointer method be called on a value?

    Answer

    When the value is addressable

    The compiler takes the address of an addressable value; a map element or a call result is not addressable.

  4. What does the second line of this program print? package main import "fmt" type Celsius float64 func (c Celsius) Fahrenheit() float64 { return float64(c)*9/5 + 32 } func (c Celsius) String() string { return fmt.Sprintf("%.1f°C", float64(c)) } type Weekday int const ( Sunday Weekday = iota Monday Tuesday ) func (d Weekday) String() string { return [...]string{"Sunday", "Monday", "Tuesday"}[d] } func main() { temp := Celsius(36.6) fmt.Println(temp, temp.Fahrenheit()) fmt.Printf("%v %d %s\n", temp, Monday, Tuesday) }

    Answer

    36.6°C 97.88000000000001 / 36.6°C 1 Tuesday

    %v uses the String method and %d asks for the weekday's number, so only the first value is formatted.

  5. How many methods named String can a type have?

    Answer

    One

    Go has no overloading: a type has one method per name.

  6. What does the compiler say about this program? package main import "fmt" type counter struct { n int } func (c *counter) Inc() { c.n++ } func (c counter) Value() int { return c.n } func main() { counters := map[string]counter{"a": {}} counters["a"].Inc() fmt.Println(counters["a"].Value()) }

    Answer

    cannot call pointer method Inc on counter

    A map element has no address, so a pointer method cannot be called on it.

  7. Which method does fmt call for %v?

    Answer

    String() string

    The fmt.Stringer interface is what %v and %s look for.

  8. What does this program print? package main import "fmt" type counter struct { n int } func (c *counter) Inc() { c.n++ } func main() { c := counter{} c.Inc() ptr := &c ptr.Inc() fmt.Println("through the address:", c.n) counters := map[string]counter{"a": {}} _ = counters }

    Answer

    through the address: 2

    c.Inc() takes the address of the local, and ptr.Inc() adds a second increment to the same counter.

  9. Why does the course recommend one receiver kind per type?

    Answer

    So the type has one method set and both values and pointers behave predictably

    Mixing receiver kinds splits the method set between T and *T, which surprises interface users.

  10. What is the receiver of a method that only reads a small struct?

    Answer

    A value receiver, usually

    A read on a small value needs no address and cannot change the caller's value.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev