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.