typestar

Interfaces in Go

Implicit satisfaction: no implements keyword.

type Shape interface {
    Area() float64
    Name() string
}

type Rect struct{ W, H float64 }

func (r Rect) Area() float64 { return r.W * r.H }
func (r Rect) Name() string  { return "rect" }

func report(shapes []Shape) {
    for _, s := range shapes {
        fmt.Printf("%s: %.2f\n", s.Name(), s.Area())
    }
}

How it works

  1. An interface lists required method signatures.
  2. Rect satisfies Shape just by having them.
  3. Code depends on the interface, not the type.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
292
Tokens
91
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 55 seconds.

Type this snippet

Step 1 of 4 in Interfaces, step 4 of 19 in Interfaces & generics.

← Previous Next →