×

go · level 2 · unit 2 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A is a function that belongs to a type.

A struct holds data, like a pet's record card. A method gives that type its own command. It is a function that belongs to the type, and you call it with a dot after a value: rex.Describe().

To write one, put the in brackets before the name: func (p Pet) Describe() string. The receiver p is the value the method was called on, so inside the method, p.Name is that pet's name.

Methods work like any other function. They can take parameters and return values, as in func (p Pet) Older(years int) int. Two different types can each have a method with the same name without mixing them up.

package main
import "fmt"
type Pet struct {
	Name string
	Age  int
}
func (p Pet) Describe() string {
	return fmt.Sprintf("%v is %v years old", p.Name, p.Age)
}
func (p Pet) Older(years int) int {
	return p.Age + years
}
func main() {
	rex := Pet{Name: "Rex", Age: 3}
	fmt.Println(rex.Describe())
	fmt.Println("In 5 years:", rex.Older(5))
}

A receiver's name is usually one short letter, often the first letter of its type.