Stage 1 · Code
Methods, Interfaces & Errors
Interfaces
Write polymorphic Go code by defining small interfaces and satisfying them implicitly — no declarations required.
What is an Interface?
An interface is a set of method signatures. Any type that implements all those methods satisfies the interface — no explicit declaration needed. This is Go's mechanism for polymorphism.
Implicit Satisfaction
Go interfaces are implicitly satisfied — you implement an interface by having the right methods, not by writing implements Shape. This decouples the definition of a type from the interfaces it satisfies.
Go's standard library favours tiny interfaces: io.Reader has one method, io.Writer has one method, fmt.Stringer has one method. Small interfaces are easier to implement, easier to compose, and easier to test. If your interface has more than three methods, consider whether it should be two interfaces.
Common Standard Interfaces
The Go standard library defines small, composable interfaces used everywhere. Implementing these makes your types work with the entire ecosystem of standard library functions.
| Interface | Method(s) | What it enables |
|---|---|---|
fmt.Stringer | String() string | Custom print output with fmt.Print |
io.Reader | Read(p []byte) (n int, err error) | Works with io.Copy, json.NewDecoder, etc. |
io.Writer | Write(p []byte) (n int, err error) | Works with fmt.Fprintf, io.Copy, etc. |
error | Error() string | Can be returned as an error value |
sort.Interface | Len, Less, Swap | Sortable with sort.Sort |
The Empty Interface
any (an alias for interface{}) has no methods, so every type satisfies it. Use it when a function genuinely needs to accept values of any type, but avoid it otherwise — it gives up compile-time type safety.
Type Assertions
A type assertion v.(T) extracts the concrete value of type T from an interface. Use the two-value form v, ok := i.(T) to check safely — the one-value form panics if the type is wrong.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.