Lesson 13 of 20 · Part 4: Types and abstraction
Interfaces
Go interfaces explained for beginners. Define behaviour, satisfy interfaces implicitly, fmt.Stringer, io.Writer, the any type, type assertions and type switches.
4 min read · Updated · Beginner friendly
What you'll learn
- Define an interface and satisfy it without any "implements" keyword
- Write functions that work with any type that has the right methods
- Use common standard interfaces like fmt.Stringer and io.Writer
- Inspect interface values with type assertions and type switches
A struct describes what a value is: its data. An interface describes what a value can do: its methods. Interfaces let you write one function that works with many different types, as long as they all have the methods you need. They are one of the most important ideas in Go.
Defining and satisfying an interface
An interface type is a list of method signatures:
package main
import (
"fmt"
"math"
)
type Shape interface {
Area() float64
Perimeter() float64
}
type Rectangle struct{ Width, Height float64 }
type Circle struct{ Radius float64 }
func (r Rectangle) Area() float64 { return r.Width * r.Height }
func (r Rectangle) Perimeter() float64 { return 2 * (r.Width + r.Height) }
func (c Circle) Area() float64 { return math.Pi * c.Radius * c.Radius }
func (c Circle) Perimeter() float64 { return 2 * math.Pi * c.Radius }
func describe(s Shape) {
fmt.Printf("%T: area %.2f, perimeter %.2f\n", s, s.Area(), s.Perimeter())
}
func main() {
shapes := []Shape{
Rectangle{Width: 3, Height: 4},
Circle{Radius: 1},
}
total := 0.0
for _, s := range shapes {
describe(s)
total += s.Area()
}
fmt.Printf("total area: %.2f\n", total)
}main.Rectangle: area 12.00, perimeter 14.00
main.Circle: area 3.14, perimeter 6.28
total area: 15.14Notice what’s missing: neither Rectangle nor Circle says it “implements” Shape. In Go, a type satisfies an interface automatically as soon as it has all of the interface’s methods. This is called implicit implementation, sometimes described as “duck typing checked by the compiler”: if it has Area and Perimeter, it is a Shape.
The describe function knows nothing about rectangles or circles. Tomorrow you could add a Triangle with the same two methods, and describe would work with it without any change.
If a type is missing a method, the compiler tells you exactly which one:
package main
type Shape interface {
Area() float64
Perimeter() float64
}
type Square struct{ Side float64 }
func (s Square) Area() float64 { return s.Side * s.Side }
func main() {
var s Shape = Square{Side: 2}
_ = s
}Square does not implement Shape (missing method Perimeter)Small interfaces are powerful
The best Go interfaces are small, often a single method. Here’s one of the most useful in the standard library, fmt.Stringer:
type Stringer interface {
String() string
}fmt.Println and friends check whether a value has a String() method and, if it does, use it to print the value:
package main
import "fmt"
type Money struct {
Cents int
Currency string
}
func (m Money) String() string {
return fmt.Sprintf("%d.%02d %s", m.Cents/100, m.Cents%100, m.Currency)
}
func main() {
price := Money{Cents: 123456, Currency: "INR"}
fmt.Println("price:", price)
fmt.Printf("in a sentence: it costs %v\n", price)
}price: 1234.56 INR
in a sentence: it costs 1234.56 INRio.Writer: one interface, many destinations
io.Writer has a single method, Write([]byte) (int, error). Files, network connections, HTTP responses, buffers and the terminal all satisfy it, so code that writes to an io.Writer can write to any of them:
package main
import (
"fmt"
"io"
"os"
"strings"
)
func writeReport(w io.Writer, name string, score int) {
fmt.Fprintf(w, "Report for %s: %d points\n", name, score)
}
func main() {
// 1. Write to the terminal
writeReport(os.Stdout, "Ada", 92)
// 2. Write into a string in memory
var sb strings.Builder
writeReport(&sb, "Grace", 88)
fmt.Print("captured: ", sb.String())
}Report for Ada: 92 points
captured: Report for Grace: 88 pointsfmt.Fprintf is like Printf but writes to the io.Writer you give it. The same writeReport could write to a file (*os.File) or a web response without changing a line. This is also what makes code easy to test: in a test you pass a strings.Builder and check what was written.
Interface values and nil
A variable of interface type holds two things: a concrete value and its type. When nothing has been assigned, both are empty and the interface is nil:
package main
import "fmt"
type Shape interface{ Area() float64 }
type Square struct{ Side float64 }
func (s Square) Area() float64 { return s.Side * s.Side }
func main() {
var s Shape
fmt.Println(s == nil)
s = Square{Side: 3}
fmt.Printf("%v %T %.0f\n", s, s, s.Area())
}true
{3} main.Square 9Calling a method on a nil interface panics, just like dereferencing a nil pointer, so check for nil when an interface might be empty.
The empty interface: any
An interface with no methods is satisfied by every type. It’s written interface{}, or more readably any:
package main
import "fmt"
func main() {
values := []any{42, "hello", 3.14, true, []int{1, 2}}
for _, v := range values {
fmt.Printf("%v (%T)\n", v, v)
}
}42 (int)
hello (string)
3.14 (float64)
true (bool)
[1 2] ([]int)any is useful when you genuinely don’t know the type in advance, as fmt.Println doesn’t. But you lose type safety: the compiler can’t help you anymore. Prefer a specific interface or generics (next lesson) when you can.
Type assertions
To get the concrete value back out of an interface, use a type assertion, value.(Type). Use the comma ok form so a wrong guess doesn’t crash the program:
package main
import "fmt"
func main() {
var v any = "gopher"
s, ok := v.(string)
fmt.Println(s, ok)
n, ok := v.(int)
fmt.Println(n, ok) // not an int: zero value and false
}gopher true
0 falseWithout ok (n := v.(int)), a wrong type causes a panic.
Type switches
When a value could be one of several types, a type switch checks them all in one go:
package main
import "fmt"
func describe(v any) string {
switch x := v.(type) {
case nil:
return "nothing"
case int:
return fmt.Sprintf("an int, doubled: %d", x*2)
case string:
return fmt.Sprintf("a string of length %d", len(x))
case fmt.Stringer:
return "something printable: " + x.String()
default:
return fmt.Sprintf("something else: %T", x)
}
}
type Point struct{ X, Y int }
func (p Point) String() string { return fmt.Sprintf("(%d,%d)", p.X, p.Y) }
func main() {
fmt.Println(describe(21))
fmt.Println(describe("hello"))
fmt.Println(describe(Point{1, 2}))
fmt.Println(describe(2.5))
fmt.Println(describe(nil))
}an int, doubled: 42
a string of length 5
something printable: (1,2)
something else: float64
nothingInside each case, x already has that case’s type, so you can use it directly. A case can also be an interface type, like fmt.Stringer above.
Good habits with interfaces
- Keep interfaces small. One to three methods is typical. Small interfaces are easy to satisfy.
- Define interfaces where they are used, not next to the types that implement them. The function that needs “something with a
Savemethod” declares that interface. - Accept interfaces, return concrete types. Functions are flexible when their parameters are interfaces and clearest when they return real types.
- Don’t create an interface until you need one. If only one type will ever be used, start with that type.
Exercises
1. Animals. Define an Animal interface with Sound() string. Create Dog and Cat types that satisfy it, put them in a []Animal, and print each sound.
Show solution
package main
import "fmt"
type Animal interface {
Sound() string
}
type Dog struct{ Name string }
type Cat struct{ Name string }
func (d Dog) Sound() string { return d.Name + " says woof" }
func (c Cat) Sound() string { return c.Name + " says meow" }
func main() {
pets := []Animal{Dog{"Rex"}, Cat{"Tom"}}
for _, p := range pets {
fmt.Println(p.Sound())
}
}Rex says woof
Tom says meow2. Make it a Stringer. Give type Temperature float64 a String() method so that fmt.Println(Temperature(21.456)) prints 21.5°C.
Show solution
package main
import "fmt"
type Temperature float64
func (t Temperature) String() string {
return fmt.Sprintf("%.1f°C", float64(t))
}
func main() {
fmt.Println(Temperature(21.456))
}21.5°CNote the conversion float64(t). Formatting t itself with %v inside String would call String again and recurse forever. go vet warns about this.
3. Sum anything numeric. Write sumAll(values []any) float64 that adds up every int and float64 in the slice and ignores everything else. Use a type switch.
Show solution
package main
import "fmt"
func sumAll(values []any) float64 {
total := 0.0
for _, v := range values {
switch n := v.(type) {
case int:
total += float64(n)
case float64:
total += n
}
}
return total
}
func main() {
fmt.Println(sumAll([]any{1, 2.5, "three", 4, true}))
}7.5Recap
- An interface lists methods; any type with those methods satisfies it, with no keyword needed.
- Functions that accept interfaces work with many types, today’s and tomorrow’s.
fmt.Stringercontrols how a value prints;io.Writerlets code write anywhere.anyaccepts every type; get the concrete value back with a type assertion or a type switch.- Keep interfaces small and define them where they are used.
Next, you’ll write type-safe code that works for many types with generics.
Finished this lesson?
Your progress is saved in this browser only.