Interfaces
An interface lists methods a type must have. Any type that has those methods automatically satisfies the interface: there's no implements keyword. That one idea lets Go code work with types it has never heard of, and it's why Go's standard library fits together so well.
Defining and satisfying an interface
package main
import (
"fmt"
"math"
)
type Shape interface {
Area() float64
Perimeter() float64
}
type Rect struct{ W, H float64 }
type Circle struct{ R float64 }
func (r Rect) Area() float64 { return r.W * r.H }
func (r Rect) Perimeter() float64 { return 2 * (r.W + r.H) }
func (c Circle) Area() float64 { return math.Pi * c.R * c.R }
func (c Circle) Perimeter() float64 { return 2 * math.Pi * c.R }
func describe(s Shape) {
fmt.Printf("%-14s area %6.2f perimeter %6.2f\n", fmt.Sprint(s), s.Area(), s.Perimeter())
}
func main() {
shapes := []Shape{Rect{3, 4}, Circle{1}, Rect{W: 10, H: 0.5}}
total := 0.0
for _, s := range shapes {
describe(s)
total += s.Area()
}
fmt.Printf("total area %.2f\n", total)
}{3 4} area 12.00 perimeter 14.00
{1} area 3.14 perimeter 6.28
{10 0.5} area 5.00 perimeter 21.00
total area 20.14Rect and Circle never mention Shape. They have the right methods, so they are Shapes. This is called structural typing ("if it has the methods, it fits"). You can define an interface for types written by someone else, even in the standard library, without changing them.
If a type is missing a method, the compiler says exactly which:
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{2}
_ = s
}# command-line-arguments
./main.go:13:16: cannot use Square{…} (value of struct type Square) as Shape value in variable declaration: Square does not implement Shape (missing method Perimeter)Small interfaces
The most important interfaces in Go have one method. The standard library's io.Reader and io.Writer are used by files, network connections, HTTP bodies, compressors, hashes, buffers and more:
type Reader interface { Read(p []byte) (n int, err error) }
type Writer interface { Write(p []byte) (n int, err error) }Because so many types satisfy them, functions that accept an io.Writer work with all of them:
package main
import (
"bytes"
"compress/gzip"
"crypto/sha256"
"fmt"
"io"
"os"
"strings"
)
func writeReport(w io.Writer) {
fmt.Fprintln(w, "orders: 42")
fmt.Fprintln(w, "revenue: 1234.50")
}
func main() {
writeReport(os.Stdout) // the terminal
var buf bytes.Buffer // memory
writeReport(&buf)
fmt.Println("buffer holds", buf.Len(), "bytes")
h := sha256.New() // a hash
writeReport(h)
fmt.Printf("sha256 %x…\n", h.Sum(nil)[:6])
var zipped bytes.Buffer
gz := gzip.NewWriter(&zipped) // a compressor, writing into a buffer
writeReport(gz)
gz.Close()
fmt.Println("gzipped to", zipped.Len(), "bytes")
n, _ := io.Copy(io.Discard, strings.NewReader("a reader of 22 bytes!!"))
fmt.Println("copied", n, "bytes")
}orders: 42 revenue: 1234.50 buffer holds 28 bytes sha256 90b7d257f925… gzipped to 53 bytes copied 22 bytes
One function, five completely different destinations. That's the payoff of small interfaces. A Go proverb puts it as: "The bigger the interface, the weaker the abstraction."
fmt.Stringer and error
Two interfaces you'll implement all the time:
type Stringer interface { String() string } // how fmt prints your type
type error interface { Error() string } // what every error ispackage main
import "fmt"
type Status int
const (
Pending Status = iota
Paid
Shipped
)
func (s Status) String() string {
switch s {
case Pending:
return "pending"
case Paid:
return "paid"
case Shipped:
return "shipped"
}
return fmt.Sprintf("Status(%d)", int(s))
}
type NotFoundError struct{ ID int }
func (e NotFoundError) Error() string { return fmt.Sprintf("order %d not found", e.ID) }
func find(id int) (Status, error) {
if id != 7 {
return 0, NotFoundError{ID: id}
}
return Shipped, nil
}
func main() {
fmt.Println(Paid, Status(9))
if s, err := find(7); err == nil {
fmt.Println("order 7 is", s)
}
if _, err := find(3); err != nil {
fmt.Println("error:", err)
}
}paid Status(9) order 7 is shipped error: order 3 not found
Interface values, type assertions and type switches
An interface value holds two things: a concrete value and its type. You can ask which type is inside:
package main
import "fmt"
func describe(v any) string {
switch x := v.(type) {
case nil:
return "nil"
case int:
return fmt.Sprintf("int %d (doubled %d)", x, x*2)
case string:
return fmt.Sprintf("string %q of length %d", x, len(x))
case []int:
return fmt.Sprintf("slice of %d ints", len(x))
case fmt.Stringer:
return "something printable: " + x.String()
default:
return fmt.Sprintf("other type %T", x)
}
}
type Color struct{ R, G, B uint8 }
func (c Color) String() string { return fmt.Sprintf("#%02x%02x%02x", c.R, c.G, c.B) }
func main() {
for _, v := range []any{42, "hello", []int{1, 2}, Color{255, 128, 0}, 3.5, nil} {
fmt.Println(describe(v))
}
var v any = "text"
s, ok := v.(string) // type assertion with "comma ok"
fmt.Println(s, ok)
n, ok := v.(int)
fmt.Println(n, ok)
}int 42 (doubled 84) string "hello" of length 5 slice of 2 ints something printable: #ff8000 other type float64 nil text true 0 false
any(another name forinterface{}) is the interface with no methods, so every value satisfies it. Use it sparingly: you lose type checking.v.(T)gets the concrete value out. Without, okit panics if the type is wrong.- A type switch handles several types at once, and a case can be an interface (
fmt.Stringer).
Design: accept interfaces, return structs
The common Go advice is to define interfaces where they're used, keep them small, and have functions accept them. That makes code easy to test, because you can pass in a fake:
package main
import (
"errors"
"fmt"
)
// The code that needs storage defines the small interface it needs.
type UserStore interface {
GetEmail(id int) (string, error)
}
type Notifier struct{ store UserStore }
func (n Notifier) Welcome(id int) (string, error) {
email, err := n.store.GetEmail(id)
if err != nil {
return "", fmt.Errorf("welcome user %d: %w", id, err)
}
return "sent welcome email to " + email, nil
}
// In production this would talk to PostgreSQL; in tests, a map is enough.
type fakeStore map[int]string
func (f fakeStore) GetEmail(id int) (string, error) {
if e, ok := f[id]; ok {
return e, nil
}
return "", errors.New("no such user")
}
func main() {
n := Notifier{store: fakeStore{1: "asha@example.com"}}
for _, id := range []int{1, 2} {
if msg, err := n.Welcome(id); err != nil {
fmt.Println("error:", err)
} else {
fmt.Println(msg)
}
}
}sent welcome email to asha@example.com error: welcome user 2: no such user
Notifier depends only on the one method it uses. A real database type, a cache, or a test fake all fit.
Checking a type satisfies an interface
To make the compiler confirm that a type implements an interface (and say so in the code), use this idiom:
var _ UserStore = fakeStore(nil) // compile error if fakeStore lacks a methodThe nil interface trap
An interface is only nil if both its type and value are nil. A nil pointer stored in an interface is not a nil interface:
package main
import "fmt"
type MyErr struct{}
func (*MyErr) Error() string { return "my error" }
func mayFail(fail bool) error {
var e *MyErr // a nil pointer
if fail {
e = &MyErr{}
}
return e // BUG: returns a non-nil interface holding a nil pointer
}
func mayFailFixed(fail bool) error {
if fail {
return &MyErr{}
}
return nil // return a literal nil
}
func main() {
fmt.Println(mayFail(false) == nil)
fmt.Println(mayFailFixed(false) == nil)
}false true
The rule: when there's no error, return nil directly, never a typed nil variable.
Practice
- Add a
Triangletype to the shapes example and include it in the slice. - Write
func countBytes(r io.Reader) (int64, error)and use it on astrings.Readerand anos.File. - Give a
Temperaturetype aString()method that prints21.5°C. - Write a
Cacheinterface withGetandSet, an in-memory implementation, and a function that uses it.
1.How does a type implement an interface in Go?
2.Why are io.Reader and io.Writer so useful?
3.What happens with n := v.(int) if v holds a string?
4.A function returns a nil *MyErr as an error. Is the result == nil?