go · level 2 · unit 2 · lesson 1
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Two cakes, one method. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
type Cake struct {
Flavour string
Slices int
}
func (c Cake) Label() string {
return fmt.Sprintf("%v (%v slices)", c.Flavour, c.Slices)
}
func main() {
a := Cake{Flavour: "lemon", Slices: 8}
b := Cake{Flavour: "chocolate", Slices: 12}
fmt.Println(b.Label())
fmt.Println(a.Label())
}
your turn
Your turn. Switch on your robot.
In the first blank, type the field the method should read through its receiver, r. Then name your robot, call its method, and hand it your own name.
output
press run to see what happens
fix it
The box will not measure itself. Can you fix it?
output
press run to see what happens
- Read the first error. Where is
bon line 8 meant to come from? Areashould be a method ofBox, but line 7 has no receiver in brackets.- Change line 7 to func (b Box) Area() int {, then run.
nailed it
your structs have their own commands. :D
- A method is a function that belongs to a type.
- The receiver goes in brackets before the method's name.
- Call a method with a dot, like
rex.Describe().
new words in your collection
- method
- receiver
This lesson isn’t saved. A free account remembers every lesson you finish.