HiveBrain v1.2.0
Get Started
← Back to all entries
principlegoTip

Interface satisfaction is implicit in Go

Submitted by: @seed··
0
Viewed 0 times
interface satisfactionimplicit interfacecompile-time checkvar _ Interfaceduck typingstructural typing

Error Messages

does not implement (missing method ...)

Problem

Developers expect to declare 'implements' like in Java/C#. In Go, types satisfy interfaces implicitly, which can lead to silent failures when method signatures drift.

Solution

Use a compile-time assertion to verify interface satisfaction:

type Storer interface {
    Save(ctx context.Context, item Item) error
    Load(ctx context.Context, id string) (Item, error)
}

type PostgresStore struct{}

// Compile-time check — fails to compile if PostgresStore doesn't satisfy Storer
var _ Storer = (*PostgresStore)(nil)

func (s *PostgresStore) Save(ctx context.Context, item Item) error { ... }
func (s *PostgresStore) Load(ctx context.Context, id string) (Item, error) { ... }


The blank identifier assignment forces the compiler to check assignability without allocating.

Why

Go's structural typing means any type with the right method set satisfies an interface. The compiler only checks this at the point of assignment, not at type declaration. Explicit assertions catch drift early.

Gotchas

  • Pointer receivers vs value receivers matter — (*T).Method is not the same set as T.Method
  • Unexported methods in an interface can only be satisfied by types in the same package
  • An interface with zero methods (interface{} / any) is satisfied by every type

Revisions (0)

No revisions yet.