Go course Lesson 6 of 6

Go from zero: an interface is a method list

An interface names the methods a function needs. Labeller asks for Label, Item has Label, and show prints latte $4.50.

Piere is one of GoByte's characters. This post was drafted by AI agents in Piere's voice, then fact checked, run and edited by the GoByte team.

Back to top

A function sometimes cares about one method and not about the rest of the struct. An interface is that list of methods. Any type with those methods can be passed in. show prints a label. It does not mention Item at all, so a discount line with its own Label method can use the same function.

Behavior is the method list#

An interface value is a method list plus a concrete value that has those methods. Labeller asks for Label() string and nothing else. Item has that method, so it can be passed to show without a keyword that says "implements". The compiler checks the method set. show cannot see Cents because Cents is not in the list. A second struct with its own Label method can use the same function. That is the object idea in Go: data lives on the struct, and the behavior you depend on is the list.

The function asks for Label, not for Item
  1. ItemLabel()latte $4.50
  2. otherno Labelrefused
package main

import "fmt"

type Item struct {
    Name  string
    Cents int
}

func (it Item) Label() string {
    return fmt.Sprintf("%s $%d.%02d", it.Name, it.Cents/100, it.Cents%100)
}

type Labeller interface {
    Label() string
}

func show(l Labeller) {
    fmt.Println(l.Label())
}

func main() {
    show(Item{Name: "latte", Cents: 450})
}
latte $4.50

The interface is satisfied by the method#

Labeller has one method, Label() string. Item has that method, from lesson 2, so an Item is a Labeller. Nobody writes "implements". The method list is the whole check, and the compiler does it.

show takes a Labeller and calls Label. main passes an Item. The printed line is latte $4.50, the same text Label built before. A second struct with its own Label method could be passed to the same show without changing show. A tax line and a drink can share one receipt printer.

Keep the list short#

An interface with one method is easy to implement and easy to read. An interface that lists every method on Item is just Item with extra steps. Name the method the caller uses. show uses Label, so Labeller lists Label. That is the object-oriented idea in Go: behavior is a method list, and the struct is the data the method closes over.

Report a mistake

Your product here? Partner with us

Back to top

Discussion

No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines

Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.