Interfaces
An interface is a named set of methods. A type satisfies it by having those methods — no implements line. Values of the interface hold a dynamic type and a value of that type.
Detailed Explanation
You want a function that writes bytes and does not care whether the destination is a file, a buffer, or a network connection. You take io.Writer. Anything with Write([]byte) (int, error) can be passed. That is the whole idea: describe behaviour, not a struct hierarchy.
The type is the method set.
type Writer interface {
Write(p []byte) (n int, err error)
}
Small interfaces are the style. io.Reader, io.Writer, error, fmt.Stringer are one or two methods. A twenty-method interface is a class in disguise and is hard to fake in tests. Compose small ones: io.ReadCloser embeds Reader and Closer.
A value is two words. An interface holds a type word and a data word. var w io.Writer is nil until you assign something. w = os.Stdout stores the type of *os.File (or the concrete type of Stdout) and the value. Calling w.Write looks up Write on that type. A nil interface is not the same as an interface that holds a nil pointer.
No inheritance tree. Two types that both have Write are not related. There is no common parent. The interface is the common parent, and it exists only where you write it — often in the package that uses the behaviour, not the package that defines the struct. That is the opposite of Java, where the class lists the interfaces it implements.
Empty interface. interface{} and its alias any have an empty method set, so every type satisfies them. They are a last resort for mixed values, not a substitute for a real method set.
What it costs. An interface call is an indirect call: the CPU cannot always inline it. For a Write on a hot path that is always *bytes.Buffer, taking *bytes.Buffer is faster. For a function that must work with files and buffers, the interface is the abstraction you want. The larger cost is a fat interface that every test must stub.
Code Examples
package main
import (
"fmt"
"io"
"os"
"strings"
)
func dump(w io.Writer, s string) error {
_, err := io.WriteString(w, s)
return err
}
func main() {
_ = dump(os.Stdout, "hello\n")
var b strings.Builder
_ = dump(&b, "hello")
fmt.Println(b.String())
}type Store interface {
Find(id string) (User, error)
Save(User) error
}
type User struct{ ID string }func closer(c io.Closer) {
if err := c.Close(); err != nil {
fmt.Println(err)
}
}Common Gotchas
Calling a method on a nil interface panics
there is no dynamic type to dispatch to. A nil `*File` stored in `io.Writer` panics inside `Write` instead, which is a different bug.
Define interfaces where they are used
a package should not export a huge interface "for all callers." The caller declares the methods it needs.
Interface equality can panic
two non-nil interfaces that hold incomparable concrete values (`[]byte`) panic on `==`.
Adding a method to an exported interface is a breaking change
every implementer in every other module must add it. Prefer a new interface.