TExcelTAD
Home › Go › Go Methods

Go Methods

A method is a function attached to a type. Go has no classes, but you can define methods on any named type you declare — structs most commonly, but also types like type Celsius float64. Methods give your types behaviour: a Rectangle can compute its Area(), a Cart can Add() an item.

Declaring a method

A method has a receiver — written in parentheses between func and the method name. The receiver is like a parameter that holds the value the method was called on.

go · try it yourself
package main

import "fmt"

type Rectangle struct {
	Width, Height float64
}

// Area has a receiver r of type Rectangle.
func (r Rectangle) Area() float64 {
	return r.Width * r.Height
}

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

func main() {
	box := Rectangle{Width: 3, Height: 4}
	fmt.Println(box.Area(), box.Perimeter())
}
12 14

Value receivers vs. pointer receivers

A value receiver (r Rectangle) gets a copy, so it cannot change the original. A pointer receiver (c *Counter) gets a pointer and can modify the value. Go automatically takes the address when you call a pointer method on an addressable variable, so you write c.Increment() either way.

go · try it yourself
package main

import "fmt"

type Counter struct {
	n int
}

func (c Counter) IncrementCopy() { c.n++ } // lost after return
func (c *Counter) Increment()   { c.n++ } // modifies the original
func (c Counter) Value() int    { return c.n }

func main() {
	var c Counter
	c.IncrementCopy()
	fmt.Println(c.Value())

	c.Increment() // Go rewrites this as (&c).Increment()
	c.Increment()
	fmt.Println(c.Value())
}
0
2
Choose a pointer receiver when… Choose a value receiver when…
the method modifies the receiver the method only reads it
the struct is large the type is small (e.g. a Point, a Celsius)
other methods of the type already use pointers (be consistent) the type should behave like an immutable value

Methods on non-struct types

Any type you declare in your package can have methods — handy for adding meaning to plain values.

go · try it yourself
package main

import (
	"fmt"
	"strings"
)

type Celsius float64

func (c Celsius) Fahrenheit() float64 {
	return float64(c)*9/5 + 32
}

type Tags []string

func (t Tags) String() string {
	return "#" + strings.Join(t, " #")
}

func main() {
	temp := Celsius(25)
	fmt.Println(temp.Fahrenheit())

	t := Tags{"go", "backend", "tips"}
	fmt.Println(t) // fmt uses our String method automatically
}
77
#go #backend #tips

A method named String() string is special: fmt calls it whenever it prints the value. (It satisfies the fmt.Stringer interface — interfaces are the next chapter.)

A small example: a shopping cart

Methods and pointer receivers together make a type that manages its own state:

go · try it yourself
package main

import "fmt"

type Item struct {
	Name  string
	Price float64
	Qty   int
}

type Cart struct {
	Items []Item
}

func (c *Cart) Add(name string, price float64, qty int) {
	c.Items = append(c.Items, Item{name, price, qty})
}

func (c Cart) Total() float64 {
	total := 0.0
	for _, it := range c.Items {
		total += it.Price * float64(it.Qty)
	}
	return total
}

func (c Cart) Count() int {
	n := 0
	for _, it := range c.Items {
		n += it.Qty
	}
	return n
}

func main() {
	var cart Cart
	cart.Add("Notebook", 4.5, 2)
	cart.Add("Pen", 1.25, 4)
	fmt.Printf("%d items, total $%.2f\n", cart.Count(), cart.Total())
}
6 items, total $14.00

Methods are promoted through embedding

When a struct embeds another type, the embedded type's methods become methods of the outer struct too. This is Go's alternative to inheritance: composition.

go · try it yourself
package main

import "fmt"

type Logger struct {
	Prefix string
}

func (l Logger) Log(msg string) {
	fmt.Println(l.Prefix + msg)
}

type Server struct {
	Logger // embedded: Server gets the Log method
	Port   int
}

func main() {
	s := Server{Logger: Logger{Prefix: "[server] "}, Port: 8080}
	s.Log("starting")
	s.Log(fmt.Sprint("listening on ", s.Port))
}
[server] starting
[server] listening on 8080

Note: You can only define methods on types declared in the same package. You cannot add a method to int or string directly — declare your own type based on them, as with Celsius above.

Test yourself

In func (a *Account) Deposit(n int), what is a?

  1. A parameter called by name
  2. The receiver
  3. The return value
  4. A package

Why does a method with a value receiver not change the original struct?

  1. Value receivers are read-only by law
  2. It receives a copy of the struct
  3. Methods cannot change fields
  4. It does change it

Which method makes fmt.Println(x) print a custom text?

  1. Print()
  2. ToString()
  3. String() string
  4. Format()