technical

Go Interfaces: Five Habits I Follow

Five habits that keep Go interfaces small, owned by the code that uses them, and clear of the typed nil trap.

An interface in Go is a type that lists a set of methods. What surprised me when I started with Go is that a type never says which interfaces it implements. In Java or C#, a class has to declare implements. In Go, if a type has the methods, it satisfies the interface.

That freedom is useful, and a few habits keep it from turning into a mess. These are the five I try to follow.

1. Define Interfaces Where They Are Used

Go interfaces generally belong in the package that uses values of the interface type, not the package that implements those values. 1

This one felt backwards to me at first. The package that calls ReadFile declares the interface, and the package that reads from disk never mentions it.

// package processor

type FileReader interface {
    ReadFile(filePath string) ([]byte, error)
}

func CountLines(reader FileReader, filePath string) (int, error) {
    data, err := reader.ReadFile(filePath)
    if err != nil {
        return 0, err
    }
    return bytes.Count(data, []byte("\n")), nil
}
// package localfs

type LocalFileReader struct{}

func (lfr LocalFileReader) ReadFile(filePath string) ([]byte, error) {
    return os.ReadFile(filePath)
}

processor doesn’t import localfs, and the interface lists only the one method processor calls. The only code that knows about both is the code that wires them together, usually main:

lines, err := processor.CountLines(localfs.LocalFileReader{}, "notes.txt")

This is close to the Dependency Inversion Principle, with a Go twist: only the consumer depends on the interface. LocalFileReader never imports FileReader and doesn’t know it exists. It just happens to have a matching ReadFile method, and the compiler checks the match where the two meet.

  classDiagram
    class processor {
        +CountLines(FileReader, string) int, error
    }
    class FileReader {
        << interface >>
        +ReadFile(string) []byte, error
    }
    class LocalFileReader {
        +ReadFile(string) []byte, error
    }
    processor --> FileReader : uses
    LocalFileReader ..|> FileReader : satisfies implicitly

It also makes CountLines easy to test: a test can pass in a fake FileReader backed by a map. A fake only tests the code that uses the interface, though. LocalFileReader still needs its own tests against a real temporary directory, and the fake should return the same kind of error as the real one when a file is missing.

For this particular case, the standard library already has the interface. io/fs defines fs.ReadFileFS, and a function that accepts an fs.FS can take os.DirFS(".") in production and an fstest.MapFS in tests. I check the standard library before writing my own.

The wiki says “generally” for a reason. When a package defines a protocol that many unrelated types implement, like io.Reader, http.Handler or database/sql/driver.Driver, the interface belongs with the protocol, not with any one consumer.

2. Keep Interfaces Small

Smaller interfaces are usually better. This follows from the Interface Segregation Principle: no code should be forced to depend on methods it doesn’t call. The standard library’s io.Reader and io.Writer show why. They have one method each, and files, network connections, buffers and gzip streams all implement them.

// package backup

type FileRetriever interface {
    RetrieveFile(filePath string) ([]byte, error)
}

type FileSaver interface {
    SaveFile(filePath string, data []byte) error
}

// Copy reads a file from one store and writes it to another.
func Copy(src FileRetriever, dst FileSaver, filePath string) error {
    data, err := src.RetrieveFile(filePath)
    if err != nil {
        return err
    }
    return dst.SaveFile(filePath, data)
}

Each parameter names only the method Copy calls on it, so the source can be a cloud bucket and the destination a local disk. The function decides how big the interface is, not a list of everything a file store could do.

3. Build Bigger Interfaces from Small Ones

When one value needs to do both, I combine the small interfaces by embedding them. Reusing FileSaver and FileRetriever from above:

type FileManager interface {
    FileSaver
    FileRetriever
}

// Snapshot keeps a copy of a file next to the original.
func Snapshot(store FileManager, filePath string) error {
    data, err := store.RetrieveFile(filePath)
    if err != nil {
        return err
    }
    return store.SaveFile(filePath+".bak", data)
}

Any type with both SaveFile and RetrieveFile satisfies FileManager without saying so. The standard library does the same thing: io.ReadWriter is io.Reader plus io.Writer.

This doesn’t undo the previous habit, as long as each function asks for the smallest interface it needs. Copy still takes a FileRetriever and a FileSaver, not two FileManagers.

4. Watch Out for Nil Pointers Inside Interfaces

The zero value of an interface is nil, and it hides a classic trap. An interface value holds two things: a concrete type and a value. It is only nil when both are unset. An interface holding a nil pointer of some concrete type is not a nil interface.

type CloudFileManager struct{}

func (c CloudFileManager) SaveFile(filePath string, data []byte) error {
    return nil // upload to cloud storage
}

func (c CloudFileManager) RetrieveFile(filePath string) ([]byte, error) {
    return nil, nil // download from cloud storage
}

func main() {
    var store FileManager // nil interface

    var cloud *CloudFileManager // nil pointer
    store = cloud               // interface now holds (*CloudFileManager, nil)

    if store != nil {
        store.SaveFile("path/to/file", []byte("data")) // panics
    }
}

store holds a nil *CloudFileManager, so the interface itself is not nil and the check passes. Then the program panics. The methods have value receivers, so Go has to dereference the pointer to copy the receiver before it can call SaveFile, and dereferencing a nil pointer panics.

With pointer receivers (func (c *CloudFileManager) SaveFile(...)), it may not panic at all. The method runs with a nil receiver and only fails if it touches a field. That is worse: the check let the call through and nothing complained. Either way, the nil check didn’t mean what I thought it meant.

This bites most often with error, and the Go FAQ uses it as its example 2:

type ValidationError struct{ Field string }

func (e *ValidationError) Error() string { return e.Field + " is required" }

func validate(input string) error {
    var err *ValidationError
    if input == "" {
        err = &ValidationError{Field: "input"}
    }
    return err // never nil, even when input is fine
}

The fix is to return a plain nil:

func validate(input string) error {
    if input == "" {
        return &ValidationError{Field: "input"}
    }
    return nil
}

So I declare error variables as error, not as a concrete error type, and return a literal nil when there is no error.

5. Accept Interfaces, Return Structs

The same wiki page has a second half to the rule from the first habit: the implementing package should return concrete types, not interfaces.

// package cloudstore

type Store struct {
    bucket string
}

func New(bucket string) *Store {
    return &Store{bucket: bucket}
}

Returning *Store lets callers use every method it has, and each caller can still declare its own small interface for the part it uses. The implementing package can add methods later without breaking anyone. It also keeps clear of the trap above: the caller gets a pointer, and s == nil means what it says.

Swapping cloudstore for localfs then means changing the line in main that builds the value. The code that uses it doesn’t change.

When I Skip the Interface

All five habits are about shaping interfaces, so it’s worth saying when not to add one. The same wiki page says “Do not define interfaces before they are used.” An interface with a single implementation and no test that needs it adds a hop every time someone jumps to the definition, and it hides which code actually runs.

So I start with the concrete type and extract an interface in the consumer when a second implementation or a test needs one. Because Go interfaces are satisfied implicitly, doing that later is cheap: the implementation doesn’t change at all.

If I could keep only one of these habits, it would be the first. Let the code that uses an interface decide what goes in it, and the other four mostly follow.