Bitpath

Lesson 1 · Unit 02

Interfaces

Satisfied without saying so, kept small, and never quite nil.

13 exercisesabout 3 min

What you practise

  • Satisfied without saying so, small interfaces (Stringer, io.Reader), the empty interface, type assertions and type switches, the nil interface that is not nil

Try a question from this lesson

Pick one

In Python any object with a speak method would do. In this Go program Dog never mentions Speaker. What happens?

Go
type Speaker interface {
  Speak() string
}

type Dog struct{}

func (d Dog) Speak() string {
  return "woof"
}

func greet(s Speaker) {
  fmt.Println(s.Speak())
}

greet(Dog{})

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Interfaces are satisfied implicitly

An interface is a set of method signatures. Any type that has those methods satisfies it automatically, even a type written years earlier in another package.

That changes who defines interfaces: the code that uses a behaviour, not the code that provides it. A function that only needs Area() declares a one-method interface and accepts anything that fits.

If a method is missing or has a different signature, the mismatch is a compile error at the point of use.

Go
type Shape interface {
  Area() float64
}

type Rect struct{ W, H float64 }

func (r Rect) Area() float64 {
  return r.W * r.H
}

var s Shape = Rect{3, 4}
fmt.Println(s.Area()) // 12

Concept

Small interfaces go far

The most used interfaces in the standard library have one method. fmt.Stringer is String() string. io.Reader is Read: fill the buffer p and report how many bytes you put there. io.Writer is its mirror image.

Files, network connections, in-memory strings and compressors all satisfy them, so a function that takes an io.Reader works with every one of those. Ask for the smallest interface that does the job.

Go
type Reader interface {
  Read(p []byte) (n int, err error)
}

type Writer interface {
  Write(p []byte) (n int, err error)
}

Concept

any, and getting back out

any is the interface with no methods, so every value satisfies it. That is how fmt.Println accepts anything. But you can do nothing with an any until you ask what is inside.

s, ok := v.(string) is a type assertion: if v holds a string, s gets it and ok is true. Without ok, a wrong guess panics. A type switch asks about several types at once.

Go
var v any = 42
s, ok := v.(string)
fmt.Println(s == "", ok) // true false

switch x := v.(type) {
case int:
  fmt.Println("int", x+1) // int 43
case string:
  fmt.Println("string", len(x))
}

9 more exercises in the app

  • 2× multiple choice
  • 3× type the answer
  • 2× fill the blanks
  • 1× order the lines
  • 1× true or false

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy