Go core
Browse topics

Methods and receivers

Version
1.27
Review
Draft

Summary#

A method is a function with a receiver. A value receiver gets a copy. A pointer receiver can change the original. The receiver base type must be defined in the same package and can be a struct or another defined type other than a pointer or interface.

Syntax#

go
func (s Stack) Size() int
func (s *Stack) Push(item string)

Example#

go
package main

import "fmt"

type stack struct{ items []string }

func (s *stack) push(item string) { s.items = append(s.items, item) }
func (s stack) size() int         { return len(s.items) }

type celsius float64

func (c celsius) fahrenheit() float64 { return float64(c)*9/5 + 32 }

func main() {
	var plates stack
	plates.push("blue")
	plates.push("green")
	fmt.Println(plates.size())
	fmt.Println(celsius(100).fahrenheit())

	sizeThen := plates.size // saves a copy of the receiver
	add := plates.push      // saves the address of plates
	add("white")
	fmt.Println(sizeThen(), plates.size())
	fmt.Println(plates.items)
}

Expected output#

Text
2
212
2 3
[blue green white]

Common mistakes#

Assigning to fields through a value receiver changes only the copy. A method value with a value receiver saves a shallow copy when it is created. For example, a copied slice keeps its original length and can still share the same backing array.

Version applicability#

Receiver declarations work from Go 1.0. The example also takes method values, which require Go 1.1 or later.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0