Lesson 1 · Unit 06
Interfaces
Describe what a value can do, and write one function for many types.
What you practise
- A set of methods, satisfied without saying so,
fmt.Stringer, one function for many types,anyand the type switch
Try a question from this lesson
Pick one
Shape is a new kind of type: it lists a method, not fields. Any type that has that method can be stored in a Shape variable. What prints?
type Rect struct {
W int
H int
}
func (r Rect) Area() int {
return r.W * r.H
}
type Shape interface {
Area() int
}
var s Shape = Rect{W: 2, H: 5}
fmt.Println(s.Area())Correct answer
10
Why
Rect has an Area() int method, and that is all Shape asks for, so a Rect fits. Calling s.Area() runs the method of whatever is stored inside: here the rectangle's, giving 2 × 5 = 10.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Interfaces
An interface is a list of methods. A struct says what a value is made of; an interface says what it can do.
A type fits an interface just by having those methods. There is no "implements" keyword: Go checks it for you, at compile time.
Through an interface variable you can only call the methods the interface lists.
type Shape interface {
Area() int
}
// a short struct fits on one line
type Square struct{ Side int }
func (s Square) Area() int {
return s.Side * s.Side
}
var sh Shape = Square{Side: 3}
fmt.Println(sh.Area()) // 9Concept
Stringer: how a value prints
The fmt package defines an interface called Stringer, with one method: String() string.
When you print a value that has that method, fmt calls it and prints the result. So a type decides for itself how it looks in output.
fmt.Sprintf works like Printf, but hands the text back instead of printing it.
type Money struct{ Cents int }
func (m Money) String() string {
return fmt.Sprintf("$%d.%02d",
m.Cents/100, m.Cents%100)
}
price := Money{Cents: 450}
fmt.Println(price) // $4.50Concept
any, and the type switch
any is the interface with no methods at all. Every value has at least no methods, so every value fits: an any can hold anything.
The price: you cannot do much with it until you ask what is inside. A type switch does that. In each case, v is the value with its real type.
func show(x any) {
switch v := x.(type) {
case int:
fmt.Println("number", v+1)
case string:
fmt.Println("text", v+"!")
default:
fmt.Println("something else")
}
}
show(41) // number 42
show("go") // text go!
show(2.5) // something else9 more exercises in the app
- 4× type the answer
- 2× multiple choice
- 1× fill the blanks
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.