principlegoTip
Interface satisfaction is implicit in Go
Viewed 0 times
interface satisfactionimplicit interfacecompile-time checkvar _ Interfaceduck typingstructural typing
Error Messages
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:
The blank identifier assignment forces the compiler to check assignability without allocating.
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.