Implicit Interface Satisfaction in Go
Go types satisfy an interface automatically by having the right methods, with no explicit implements declaration. This structural typing decouples implementations from interface definitions, so you can define interfaces around how you use a type without…
WHY IT EXISTS Many languages require a type to explicitly declare that it implements an interface, which couples the implementer to every interface it might satisfy and forces interface decisions up front. Go avoids this so that interfaces can be small, defined where they are consumed, and satisfied by types that were written without knowledge of them.
THE MENTAL MODEL Think of an interface as a checklist of method signatures. Any type whose method set contains all those signatures satisfies the interface automatically. There is no implements keyword and no link recorded in the type's definition; satisfaction is checked structurally by the compiler wherever the type is used as the interface.
HOW IT WORKS The compiler verifies, at the point you assign or pass a concrete type where an interface is expected, that the type's method set covers the interface. If it does, the assignment compiles and an interface value holding the concrete type and its method table is created. Because the check is structural, the same type can satisfy many unrelated interfaces, and you can write an interface after the types that satisfy it already exist.
WHEN IT MATTERS It matters most for decoupling and testing. You define a tiny interface like one with a single Read method right next to the function that needs it, and pass real or fake implementations interchangeably. It enables Go's preference for small interfaces and the standard library's reuse of io.Reader and io.Writer everywhere.
ONE CONCRETE EXAMPLE The standard io.Writer interface declares one method, Write taking a byte slice and returning an int and an error. A bytes.Buffer, an os.File, and an http.ResponseWriter all have that method, so all three satisfy io.Writer without ever mentioning it. A function accepting an io.Writer can write to a file, a network response, or an in-memory buffer in tests, and none of those types were modified to opt in.
Read the original → go.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.