Functions that belong to a type

A struct holds data. Often you also want actions that belong to that data, like "work out the total of this order". You could write a normal function that takes an Order. Go also lets you attach the function to the type itself. A function attached to a type is called a method.

package main

import "fmt"

type Order struct {
	Price    int
	Quantity int
}

func (o Order) Total() int {
	return o.Price * o.Quantity
}

func main() {
	a := Order{Price: 12, Quantity: 3}
	b := Order{Price: 5, Quantity: 10}
	fmt.Println(a.Total())
	fmt.Println(b.Total())
}

Output:

36
50

A method looks like a function with one extra part before its name: (o Order). This part is the receiver. It says which type the method belongs to, and it gives a name, o, to the value the method was called on.

You call a method with a dot, like a field: a.Total(). Inside the method, o is a. In the next call, b.Total(), o is b. The receiver name is usually one or two letters, often the first letter of the type.

Parameters, and methods that call methods

A method can take parameters and return values, just like a function. It can also call other methods of the same value:

package main

import "fmt"

type Order struct {
	Price    int
	Quantity int
}

func (o Order) Total() int {
	return o.Price * o.Quantity
}

func (o Order) WithFee(fee int) int {
	return o.Total() + fee
}

func main() {
	a := Order{Price: 12, Quantity: 3}
	fmt.Println(a.WithFee(5))
}

Output:

41

WithFee asks o for its total and adds the fee: 36 + 5 is 41.

If you call a method that the type does not have, the program does not compile:

package main

import "fmt"

type Order struct {
	Price    int
	Quantity int
}

func (o Order) Total() int {
	return o.Price * o.Quantity
}

func main() {
	a := Order{Price: 12, Quantity: 3}
	fmt.Println(a.Sum())
}

Output:

# command-line-arguments
./main.go:16:16: a.Sum undefined (type Order has no field or method Sum)

Methods on other types

Methods are not only for structs. You can add one to any type you declare yourself. Here Celsius is a new type based on float64:

package main

import "fmt"

type Celsius float64

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

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

Output:

77

Two different types may each have a method with the same name. A Rect and a Circle can both have an Area method, and Go knows which one to call from the type of the value. The Interfaces lesson builds on this.

One thing to keep in mind: the receiver o is a copy of the value you called the method on. That is fine for methods that only read fields, like the ones above. A method that changes fields needs something more, which the next lesson, Pointers, explains.

In the exercise, finish the Area method of Rect and write a second method, Perimeter.