Understand the contract

An interface specifies behavior through a set of methods. A type satisfies it implicitly when its method set includes those methods. Define a small interface where a consumer needs that behavior, rather than creating an interface for every struct before any consumer requires one.

The named function accepts a Namer and only calls Name. User satisfies the interface with a value receiver, so both User and *User can provide that behavior. If Name had a pointer receiver, a User value would not satisfy Namer, although an ordinary method call may take an address automatically.

Work through the example

The example prints Ada without named knowing how a user stores its name. An alternative type can implement Name using a different representation. This gives a useful substitution point when the consumer needs behavior; direct struct parameters remain a good choice when no substitution is necessary.

package main

import "fmt"

type Namer interface { Name() string }
type User struct { Display string }

func (u User) Name() string { return u.Display }
func named(value Namer) string { return value.Name() }

func main() { fmt.Println(named(User{Display: "Ada"})) }

Watch this boundary

An interface value is nil only when it has neither a dynamic type nor a dynamic value. An interface holding a typed nil pointer is not nil. Calling a method through it can still panic if that method dereferences the pointer. Return a literal nil error for success, rather than a typed nil pointer.

Practice with a changed input

Create a second Namer type and pass it to named. Then inspect an empty interface and an interface holding (*User)(nil), comparing each with nil without invoking methods.

References & further reading

Need help with your Go backend?

I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.

Explore Go consulting services