Go · Stage 7 – Structuring Data · Lesson 43 of 64

Struct Methods

Attach a function to values of one struct type.

Go code

type Dog struct { Name string }

func (d Dog) Speak() {
    fmt.Println(d.Name, "says woof")
}

d := Dog{Name: "Milo"}
d.Speak()
Line-by-line explanation
  1. Dog has a Name field.
  2. The receiver d attaches Speak to Dog.
  3. The method reads d.Name.
  4. Dot notation calls it on one value.
Expected output
Milo says woof

This is the expected result.

Tiny Practice

Starter scenario

Call the existing Speak method.

Go code

d := Dog{Name: "Milo"}
d.CHANGE_ME
Line-by-line explanation
  1. The Dog value is ready.
  2. The method call is missing.
Expected output
(complete the starter first)

The starter intentionally contains CHANGE_ME.

Hint
  1. Use Speak.
  2. Add round brackets.
  3. Capitalization matters.
Show Solution

Go code

d := Dog{Name: "Milo"}
d.Speak()
Line-by-line explanation
  1. D stores a Dog.
  2. Speak is called on it.
Expected output
Milo says woof

This is the expected result.