Interfaces and Go errors

Describe what a type can do with an interface, satisfy it implicitly, and handle failure with error values. This is how Limiter, TokenBucket and FixedWindow fit together.

Learning outcomes

  • Define an interface and satisfy it implicitly.
  • Accept interfaces and return structs.
  • Return, create, wrap and check errors with errors.New, fmt.Errorf and errors.Is.
  • Explain why a nil pointer inside an interface is not a nil interface.
  • Write the Limiter interface and two types that satisfy it.

Why interfaces matter

In the previous lessons, you learned how to define structs and attach methods to them. A struct describes data, and its methods describe operations that can be performed using that data.

Now consider the rate limiter you are building. Week 1 will eventually contain more than one rate-limiting algorithm:

  • A token bucket that allows requests while tokens remain.
  • A fixed-window counter that allows a limited number of requests during each time window.
  • Test implementations that always allow requests or count how often a method is called.

All these types can answer the same question:

Can this request proceed?

The implementation differs, but the operation is the same. Code that uses a rate limiter should not need to know which algorithm is behind it.

This is the problem interfaces solve in Go. An interface describes a set of methods that a type must provide. It defines behavior without prescribing the data or implementation behind that behavior.

An interface lets one part of a program depend on what another part can do, rather than on its concrete implementation.

Defining an interface

An interface declaration lists method signatures. It does not contain the method implementations or the fields of a struct.

Here is the interface for our rate limiter:

backend/internal/ratelimit/limiter.go
package ratelimit

type Limiter interface {
    Allow(key string) bool
}

This interface says that any type satisfying Limiter must have a method named Allow that:

  • Accepts one string argument named key.
  • Returns one boolean value.

The method signature is the contract. The interface does not say how the implementation decides whether a request is allowed.

A token bucket might inspect available tokens. A fixed-window counter might inspect the number of requests in the current window. Both can satisfy the same contract.

Implementing an interface implicitly

In some languages, a type must explicitly declare that it implements an interface. Go does not require that declaration.

A type satisfies an interface automatically when its method set contains all the methods required by that interface, with matching signatures.

Consider a token bucket:

backend/internal/ratelimit/token_bucket.go
package ratelimit

type TokenBucket struct {
    Capacity int
    Tokens   int
}

func (b *TokenBucket) Allow(key string) bool {
    if b.Tokens <= 0 {
        return false
    }

    b.Tokens--
    return true
}

The pointer type *TokenBucket has an Allow(string) bool method. Therefore, *TokenBucket satisfies Limiter.

We can also implement a fixed-window limiter:

backend/internal/ratelimit/fixed_window.go
package ratelimit

type FixedWindow struct {
    Limit int
    Count int
}

func (w *FixedWindow) Allow(key string) bool {
    if w.Count >= w.Limit {
        return false
    }

    w.Count++
    return true
}

The pointer type *FixedWindow also satisfies Limiter.

Notice that neither type mentions Limiter in its declaration. There is no implements keyword and no explicit registration step.

This is called implicit interface satisfaction. A type satisfies an interface because its methods match the contract, not because it declares an intention to implement it.

Calling implementations through an interface

You can declare a variable whose type is an interface:

go
package main

import "fmt"

type Limiter interface {
    Allow(key string) bool
}

type TokenBucket struct {
    Tokens int
}

func (b *TokenBucket) Allow(key string) bool {
    if b.Tokens == 0 {
        return false
    }

    b.Tokens--
    return true
}

type FixedWindow struct {
    Limit int
    Count int
}

func (w *FixedWindow) Allow(key string) bool {
    if w.Count >= w.Limit {
        return false
    }

    w.Count++
    return true
}

func main() {
    var limiter Limiter

    limiter = &TokenBucket{Tokens: 2}
    fmt.Println(limiter.Allow("user-42"))
    fmt.Println(limiter.Allow("user-42"))

    limiter = &FixedWindow{Limit: 1}
    fmt.Println(limiter.Allow("user-42"))
}

The variable limiter has the interface type Limiter, but it can hold values of different concrete types.

When you call limiter.Allow, Go dispatches the call to the method belonging to the concrete value currently stored in the interface.

The caller only knows about Allow. It does not need to know whether the implementation uses tokens, counters, or another algorithm.

That separation becomes useful when you build the HTTP middleware later. The middleware can call Allow without knowing which rate-limiting algorithm the application selected.

The dependency structure

The Limiter interface sits in the middle, with TokenBucket, FixedWindow and a test fake implementing it, while HTTP middleware depends only on Limiter.The Limiter interface sits in the middle, with TokenBucket, FixedWindow and a test fake implementing it, while HTTP middleware depends only on Limiter.

The important relationship is that the middleware depends on the interface, not on TokenBucket or FixedWindow.

This means you can replace one implementation with another without rewriting the middleware, provided the replacement satisfies the same contract.

Accept interfaces, return structs

A common Go design guideline is:

  • Accept interfaces when a function only needs a particular behavior.
  • Return concrete types when a function is responsible for constructing a value.

For example, imagine a function that checks whether a request should proceed:

go
func ProcessRequest(limiter Limiter, key string) bool {
    return limiter.Allow(key)
}

The function accepts Limiter, not *TokenBucket.

It does not need to know how the limiter works. It only needs the ability to call Allow.

You can pass either implementation:

go
bucket := &TokenBucket{Tokens: 5}
window := &FixedWindow{Limit: 10}

ProcessRequest(bucket, "user-42")
ProcessRequest(window, "user-42")

A constructor, on the other hand, should generally return the concrete type it creates:

go
func NewTokenBucket(capacity int) *TokenBucket {
    return &TokenBucket{
        Capacity: capacity,
        Tokens:   capacity,
    }
}

Returning *TokenBucket preserves access to its complete API. The caller can decide whether to keep the concrete type or assign the result to an interface.

This guideline is not an absolute rule. Sometimes returning an interface is appropriate, particularly when a package intentionally hides all implementation details. But returning an interface by default can unnecessarily restrict what callers can do with the returned value.

Why the consumer should define the interface

Suppose the rate limiter package exports TokenBucket, FixedWindow, and Limiter.

A separate HTTP package only needs the Allow operation. It does not need every possible operation that a rate-limiting package might expose.

The HTTP package can define its own interface:

backend/internal/httpx/limiter.go
package httpx

type Limiter interface {
    Allow(key string) bool
}

This interface has the same method set as the one in the rate limiter package. Both concrete implementations satisfy it automatically.

Why define the interface in the HTTP package?

Because the HTTP package is the consumer. It knows exactly what behavior it needs. The rate limiter package should not have to predict every possible consumer and define interfaces for all of them.

This also keeps interfaces small. An interface with one method is often more useful than a large interface containing many operations that a consumer does not need.

Small interfaces in the standard library

Go's standard library uses small interfaces extensively.

io.Reader

The io.Reader interface represents something that can provide bytes:

go
type Reader interface {
    Read(p []byte) (n int, err error)
}

Files, network connections, and other types can implement this method. A function that accepts io.Reader can work with all of them without knowing their concrete types.

fmt.Stringer

The fmt.Stringer interface describes a type that can provide a string representation:

go
type Stringer interface {
    String() string
}

If a type implements String() string, formatting functions such as fmt.Println can use that representation.

sort.Interface

The sort.Interface interface describes a collection that can be sorted:

go
type Interface interface {
    Len() int
    Less(i, j int) bool
    Swap(i, j int)
}

It does not require the collection to use a particular data structure. It only requires the operations needed by the sorting algorithm.

These examples demonstrate an important design principle: define the smallest useful behavior that a consumer needs.

Interface embedding

An interface can include another interface by listing its name in the interface body. This is called interface embedding.

For example:

go
type Reader interface {
    Read(p []byte) (int, error)
}

type ReadCloser interface {
    Reader
    Close() error
}

A type satisfies ReadCloser if it has both the Read and Close methods.

Embedding lets you compose contracts without repeating method signatures.

You do not need interface embedding for the Week 1 limiter. Its single-method interface is already sufficient.

Compile-time interface checks

Implicit satisfaction is convenient, but it can sometimes make a missing method less obvious.

A compile-time interface check makes the intended relationship explicit:

go
var _ Limiter = (*TokenBucket)(nil)
var _ Limiter = (*FixedWindow)(nil)

This declares variables of type Limiter whose values are the corresponding typed nil pointers. The blank identifier discards the variables.

The declarations are useful because the compiler must verify that each pointer type satisfies Limiter. If a required method is removed or its signature changes, compilation fails at this declaration.

These checks do not create runtime objects or allocate token buckets.

Place them near the concrete implementation when you want to document which interfaces the type is expected to satisfy.

The nil interface gotcha

Interfaces have a behavior that surprises many Go developers.

An interface value is not simply a pointer to an object. Conceptually, it stores two pieces of information:

  1. The concrete type stored in the interface.
  2. The concrete value stored in the interface.

For example, when you assign a *TokenBucket to a Limiter, the interface records that its concrete type is *TokenBucket and stores the pointer value.

A zero-value interface contains neither a concrete type nor a concrete value. It is nil.

go
var limiter Limiter

fmt.Println(limiter == nil)

This prints true.

Now consider a typed nil pointer:

go
var bucket *TokenBucket

var limiter Limiter = bucket

fmt.Println(bucket == nil)
fmt.Println(limiter == nil)

The output is:

true
false

Why?

The pointer variable bucket is nil, but assigning it to limiter gives the interface a concrete type: *TokenBucket.

The interface therefore contains a type even though its stored pointer is nil. Since the interface has a dynamic type, the interface itself is not nil.

Visualising the interface value

Show a nil interface as an empty pair, and an interface holding a typed nil pointer as a pair whose type slot contains *TokenBucket while its value slot contains nil.Show a nil interface as an empty pair, and an interface holding a typed nil pointer as a pair whose type slot contains *TokenBucket while its value slot contains nil.

This distinction matters when returning interfaces from functions.

Consider:

go
func NewLimiter() Limiter {
    var bucket *TokenBucket
    return bucket
}

The function returns a non-nil interface containing a nil *TokenBucket.

A caller checking if limiter == nil will not detect the nil pointer.

A safer implementation is:

go
func NewLimiter() Limiter {
    return &TokenBucket{
        Capacity: 10,
        Tokens:   10,
    }
}

If construction can fail, return an error rather than returning a typed nil pointer as a successful interface value.

Go errors are values

A function that can fail needs a way to communicate failure to its caller.

In Go, the conventional approach is to return an error value alongside the result.

The built-in error type is an interface:

go
type error interface {
    Error() string
}

A value satisfies error if it implements the Error() string method.

The standard library provides several ways to create and work with errors. The simplest is errors.New:

go
package main

import (
    "errors"
    "fmt"
)

func main() {
    err := errors.New("rate limit exceeded")

    if err != nil {
        fmt.Println(err.Error())
    }
}

errors.New creates an error value containing the supplied message.

Errors are ordinary values. You can assign them to variables, pass them to functions, return them, and compare them under the rules of Go's error-handling APIs.

Returning a value and an error

A function that might fail commonly returns two values:

go
func FindLimit(key string) (int, error) {
    if key == "" {
        return 0, errors.New("key is required")
    }

    return 100, nil
}

The first result is the requested value. The second is the error.

Returning nil as the error means the operation succeeded. Returning a non-nil error means the operation failed.

The caller should check the error immediately:

go
limit, err := FindLimit("user-42")
if err != nil {
    fmt.Println("could not find limit:", err)
    return
}

fmt.Println("limit:", limit)

This is the standard Go pattern. Do not use the returned value as though it were valid before checking the error.

A function may return a zero value alongside an error. For an integer, that is usually 0; for a pointer, it is usually nil; for a slice, it may be nil. The caller should treat the result as unsuccessful when the error is non-nil unless the function's documentation explicitly says otherwise.

Why Go uses error values instead of exceptions

In languages with exceptions, a function can fail by throwing an exception. The error may travel up the call stack until some surrounding code catches it.

Go takes a different approach for ordinary failures. Functions return errors explicitly, so their signatures show that failure is a possible outcome.

Compare these two signatures:

go
func FindLimit(key string) int
go
func FindLimit(key string) (int, error)

The second signature communicates that the caller must account for a possible failure.

This makes error handling visible in the code. It also gives the caller control over whether to retry, return an HTTP error, use a fallback, or stop processing.

An invalid user key, a missing database record, a failed Redis operation, and a malformed request are all examples of ordinary failures that should generally be represented as errors.

When should you panic?

A panic is a mechanism for stopping normal execution and unwinding the current goroutine's call stack. It is not the normal way to report a failed operation.

In a backend service, panicking because Redis is unavailable or because a user supplied an invalid key is usually a poor choice. These failures are expected possibilities, and the application should handle them deliberately.

Panic is appropriate in limited situations, such as:

  • A programmer has violated an invariant that makes continued execution unsafe.
  • A package cannot continue because of an unrecoverable programming error.
  • A package intentionally uses panic for a narrowly scoped internal mechanism, with a clear recovery boundary.

For normal service code, return an error.

Do not add recover everywhere to hide panics. Recovery is useful at deliberate boundaries, such as protecting a server from one handler panic terminating an entire process, but it does not replace correct error handling.

Wrapping errors with context

An error message often needs more information than the original failure provides.

Suppose a function reads a rate limit from Redis. The Redis client returns an error, but the caller also needs to know which operation failed.

Use fmt.Errorf with the %w verb to wrap an existing error:

go
package ratelimit

import (
    "fmt"
)

func readCount(key string) (int64, error) {
    count, err := loadCount(key)
    if err != nil {
        return 0, fmt.Errorf("read request count for key %q: %w", key, err)
    }

    return count, nil
}

The %w verb wraps the original error. The resulting error includes additional context while preserving the original error in its chain.

This is different from using %v:

go
fmt.Errorf("read request count: %v", err)

The %v version formats the original error into a message, but it does not wrap it. Code that examines the error chain cannot discover the original error through that formatting operation.

Use %w when callers may need to inspect the underlying error.

Avoid logging and returning the same error

A common mistake is to log an error at every function boundary and then return it to the caller.

For example:

go
func loadConfiguration() error {
    err := readConfigurationFile()
    if err != nil {
        log.Println("could not read configuration:", err)
        return err
    }

    return nil
}

If the caller logs the returned error too, the same failure appears multiple times.

A better approach is to add useful context as the error moves upward, then log it at the boundary that has enough information to decide what action to take.

For an HTTP handler, that boundary may be where the application converts an internal failure into an HTTP response. For a background worker, it may be the worker's top-level processing loop.

Return errors from lower-level functions. Avoid logging and returning the same error unless there is a specific reason to do both.

Sentinel errors and errors.Is

Sometimes callers need to distinguish a particular failure from other failures.

A sentinel error is a package-level error value representing a known condition.

For example:

backend/internal/ratelimit/errors.go
package ratelimit

import "errors"

var ErrNotFound = errors.New("rate limit entry not found")

A function can return this error when a requested entry does not exist:

go
func FindBucket(key string) (*TokenBucket, error) {
    if key == "" {
        return nil, ErrNotFound
    }

    return &TokenBucket{
        Capacity: 10,
        Tokens:   10,
    }, nil
}

The caller can use errors.Is to check whether an error matches a known condition:

go
bucket, err := FindBucket("")

if errors.Is(err, ErrNotFound) {
    fmt.Println("bucket does not exist")
    return
}

if err != nil {
    fmt.Println("could not find bucket:", err)
    return
}

fmt.Println(bucket)

errors.Is checks the error itself and the errors wrapped inside it. This means the check continues to work even if another function adds context:

go
return nil, fmt.Errorf("lookup failed: %w", ErrNotFound)

The caller can still identify ErrNotFound using errors.Is.

Use sentinel errors for conditions that callers genuinely need to distinguish. Do not create a global error variable for every possible message.

Inspecting error types with errors.As

Sometimes you need more than a yes-or-no check. You may need to extract a structured error value.

errors.As searches the error chain for a value assignable to a target type.

For example, a package might define a structured error containing an HTTP status code:

go
package httpx

type StatusError struct {
    Code    int
    Message string
}

func (e *StatusError) Error() string {
    return e.Message
}

A function can return this error:

go
func ValidateKey(key string) error {
    if key == "" {
        return &StatusError{
            Code:    400,
            Message: "key is required",
        }
    }

    return nil
}

A caller can inspect the error:

go
err := ValidateKey("")

var statusErr *StatusError
if errors.As(err, &statusErr) {
    fmt.Println(statusErr.Code)
    fmt.Println(statusErr.Message)
    return
}

if err != nil {
    fmt.Println("unexpected error:", err)
}

Notice that the target passed to errors.As is a pointer to a variable of the target error type. errors.As populates that variable when it finds a matching error in the chain.

Use errors.Is when checking for a known error value or condition. Use errors.As when you need to inspect a particular error type.

Using interfaces to make tests simpler

Interfaces are particularly useful when writing tests.

Suppose your HTTP middleware depends on this interface:

go
type Limiter interface {
    Allow(key string) bool
}

A production implementation might use a token bucket. But middleware tests should not need to construct a real token bucket or reproduce its algorithm.

You can create a fake implementation that always allows requests:

go
type AlwaysAllow struct{}

func (AlwaysAllow) Allow(key string) bool {
    return true
}

You can also create a fake that counts calls:

go
type CountingLimiter struct {
    Calls int
}

func (l *CountingLimiter) Allow(key string) bool {
    l.Calls++
    return l.Calls <= 2
}

Both satisfy Limiter.

Here is a small function that demonstrates how the middleware's dependency can be tested without a production implementation:

go
func ShouldProcess(limiter Limiter, key string) bool {
    return limiter.Allow(key)
}

A test can use the counting fake:

go
package ratelimit

import "testing"

func TestShouldProcess(t *testing.T) {
    limiter := &CountingLimiter{}

    if !ShouldProcess(limiter, "user-42") {
        t.Fatal("first request should be allowed")
    }

    if !ShouldProcess(limiter, "user-42") {
        t.Fatal("second request should be allowed")
    }

    if ShouldProcess(limiter, "user-42") {
        t.Fatal("third request should be rejected")
    }

    if limiter.Calls != 3 {
        t.Fatalf("expected 3 calls, got %d", limiter.Calls)
    }
}

The test controls the behavior of the dependency. It can verify how the code responds to allowed and rejected requests without depending on token calculations, storage, or external services.

This is one of the practical benefits of small interfaces: they make dependencies replaceable.

A fake is a lightweight test implementation with predictable behavior. It is not necessarily a complete simulation of the production implementation. Its purpose is to isolate the behavior being tested.

The empty interface and any

Go also has an interface with no methods:

go
interface{}

Because it requires no methods, every Go value satisfies it.

Go provides the alias any for this type:

go
func PrintValue(value any) {
    fmt.Println(value)
}

This function can accept a string, an integer, a struct, or a pointer.

However, any does not provide useful behavior by itself. Once a value is stored as any, the caller may need to determine its concrete type before performing type-specific operations.

One way to do that is a type switch:

go
func Describe(value any) string {
    switch v := value.(type) {
    case string:
        return "string: " + v
    case int:
        return fmt.Sprintf("integer: %d", v)
    case bool:
        return fmt.Sprintf("boolean: %t", v)
    default:
        return fmt.Sprintf("unknown type: %T", v)
    }
}

The expression value.(type) is only valid inside a type switch. Each case matches a concrete type, and the variable v has that type within the matching case.

Type switches are useful when a function intentionally accepts several unrelated types and needs different behavior for each one.

Do not use any as a shortcut when a small interface would express the required behavior more clearly. For example, a rate limiter should accept Limiter, not any, because the code needs the Allow operation.

Putting the design together

The Week 1 rate limiter gives you a practical example of how these ideas fit together.

The rate-limiting package owns concrete implementations such as TokenBucket and FixedWindow. Each implementation exposes an Allow method.

The HTTP package only needs to know whether a request is allowed. It can define a small Limiter interface containing that method.

The middleware accepts the interface and calls Allow. It does not need to know which algorithm is active.

The tests provide fakes that implement the same interface. This lets them verify middleware behavior without depending on the production algorithm.

Errors follow the same design philosophy. A function reports failure through an error value. Callers decide whether to add context, inspect a known error with errors.Is, extract a structured error with errors.As, retry, or return a response.

The result is code with explicit contracts and replaceable dependencies. You can change the implementation without forcing every consumer to change with it.

Common mistakes to avoid

  • Thinking a type must declare that it implements an interface: Go checks method sets automatically.
  • Defining a large interface too early: Start with the methods the consumer actually needs.
  • Accepting a concrete implementation unnecessarily: If a function only needs Allow, accept Limiter.
  • Returning an interface from every constructor: Return the concrete type unless hiding the implementation is an intentional design choice.
  • Assuming a typed nil pointer makes a nil interface: The interface can still contain a concrete type.
  • Ignoring returned errors: Check them immediately and do not use failed results as though they were valid.
  • Wrapping errors with %v when callers need to inspect them: Use %w to preserve the error chain.
  • Comparing error messages as strings: Use errors.Is or errors.As when checking error conditions or types.
  • Using panic for ordinary service failures: Return errors for expected failures such as missing records or unavailable dependencies.
  • Logging the same error at every layer: Add context as needed and log at the boundary responsible for handling the failure.

Knowledge assessment

Question 1 of 4

How does *TokenBucket satisfy a Go interface named Limiter without explicitly declaring that it implements the interface?

Pick an answer, then say how sure you are.

Practical applications

  • Practice exercise 1.8: Use interfaces and errors in a small Go program, reinforcing implicit interface satisfaction and explicit error handling.
  • Exercise 1.11: Apply interface-based design when working with the rate limiter implementations.
  • Exercise 1.14: Use the Limiter contract and error-handling patterns in the rate-limiting code.
  • Exercise 1.18: Build HTTP middleware that depends on the Limiter interface rather than a concrete rate-limiting implementation.
  • Exercise 1.22: Apply interfaces, fakes, and error handling in the broader Week 1 implementation.

References

Everything above is explained on this page; these are where it comes from (Go 1.2x).

Finished Lesson 1.7?