Interfaces Are Satisfied Implicitly
Define small one-method interfaces, satisfy them without implements keywords, and swap real dependencies for bytes.Buffer in tests. After this, you can decouple callers from concrete types.
Course content
Sign in to save your progress.
-
Interfaces and Standard Abstractions
-
Interfaces Are Satisfied Implicitly
-
Read and Stream With io.Reader and io.Writer
-
-
-
Context, Timeouts, and Cancellation
-
Use context.Context for Deadlines and Cancellation
-
Set Timeouts on HTTP Clients and Server Handlers
-
-
-
Goroutines, Channels, and Coordination
-
Run Concurrent Work Safely With sync.WaitGroup
-
Coordinate Pipelines and Timeouts With Channels and select
-
-
-
Structured Logging and Databases
-
Write Structured JSON Logs With log/slog
-
Query Relational Data Safely With database/sql
-
-
-
Middleware and Production-Ready Services
-
Wrap HTTP Handlers With Middleware
-
Build a Multi-Route Service With Graceful Shutdown
-
-
-
Generics, Transactions, Timers, and Test Doubles
-
Generics, Constraints, and slices/maps Packages
-
SQL Transactions and Connection Pool Limits
-
Timers, Tickers, and Avoiding time.After Leaks
-
Testing With Interface Fakes, t.TempDir, and testdata
-
-
In Java or C#, a class must explicitly announce implements ReceiptSender before anyone can pass it to a function expecting a ReceiptSender. Go flips that model around: interfaces are satisfied implicitly. Any type that defines the required methods automatically satisfies the interface—even types from the standard library or third-party SDKs you cannot edit.
That design keeps Go interfaces tiny (often just one method) and lets you define them in the package that uses a dependency instead of the package that provides it. It also introduces one famous runtime trap—the typed-nil interface—that catches almost every developer once.
Skip ahead
If you already define small consumer-side interfaces, verify satisfaction with var _ Interface = (*Type)(nil), and know why returning a typed nil pointer as error breaks err == nil, continue to "Read and Stream With io.Reader and io.Writer."
Experiment 1: Consumer-side interfaces keep billing code testable
Suppose your billing package needs to email a receipt after charging a card. Instead of importing a 20-method SendGrid SDK directly into billing, declare a 1-method interface right next to the function that calls it:
package billing
type ReceiptSender interface {
SendReceipt(email string, cents int64) error
}
func ChargeAndNotify(s ReceiptSender, email string, cents int64) error {
// ... charge logic ...
return s.SendReceipt(email, cents)
}
In production, your real email client satisfies ReceiptSender without ever importing billing. In unit tests, you write a 5-line in-memory fake—no mocking framework needed:
type fakeSender struct {
sent []string
}
func (f *fakeSender) SendReceipt(email string, cents int64) error {
f.sent = append(f.sent, email)
return nil
}
// Compile-time check: fails to build if *fakeSender drifts out of sync!
var _ ReceiptSender = (*fakeSender)(nil)
Look at that last line: var _ ReceiptSender = (*fakeSender)(nil) costs zero runtime memory and asks the compiler to yell immediately if someone renames SendReceipt or changes its arguments.
Experiment 2: The typed-nil interface trap
Under the hood, a Go interface value is a two-word pair: (concrete type, concrete value). An interface is only == nil when both slots are nil. Watch what happens when a function declares a typed pointer var e *MyErr and returns it directly as an error:
package main
import "fmt"
type MyErr struct{ msg string }
func (e *MyErr) Error() string { return e.msg }
func broken(fail bool) error {
var e *MyErr
if fail {
e = &MyErr{msg: "boom"}
}
return e // BUG: when fail==false, returns (*MyErr)(nil), NOT nil!
}
func fixed(fail bool) error {
if fail {
return &MyErr{msg: "boom"}
}
return nil
}
func main() {
err1 := broken(false)
fmt.Printf("broken(false)==nil: %v (type=%T)\n", err1 == nil, err1)
err2 := fixed(false)
fmt.Printf("fixed(false)==nil: %v\n", err2 == nil)
}
broken(false)==nil: false (type=*main.MyErr)
fixed(false)==nil: true
Trace why err1 == nil printed false even though fail was false:
ewas a typednilpointer of type*MyErr.- Returning
eas anerrorinterface packed(type=*main.MyErr, value=nil)into the interface. - Because the type slot was non-nil, every caller checking
if err != nilentered its error path on a successful call—and if it tried callingerr.Error(), dereferencinge.msgwould panic!
Always return an explicit untyped nil on success—never a typed pointer variable.
Experiment 3: Type assertions and type switches without panicking
When you need to check what concrete value sits inside an interface, a single-value assertion x.(string) panics if x holds an int. Always use the two-value "comma-ok" assertion (or a type switch):
if s, ok := val.(string); ok {
fmt.Println("string:", s)
}
switch v := val.(type) {
case int:
fmt.Println("int:", v)
case string:
fmt.Println("string:", v)
default:
fmt.Printf("other: %T\n", v)
}
Accept interfaces, return concrete structs
A widely followed Go rule is: accept interfaces, return concrete structs. Accepting an io.Reader makes your parser work with files, HTTP bodies, and strings.Reader in tests. Returning a concrete *OrderStore instead of a huge OrderStoreInterface lets callers inspect concrete fields and define their own 1-method interfaces for just the method they need.
Common mistakes
- Defining a 15-method interface up front next to the struct: Forces every test fake to implement 14 unused methods. Keep interfaces 1–3 methods wide and put them in the consumer package.
- Returning a typed
nilpointer aserror: Causesif err != nilto trigger on successful calls. Always writereturn nilexplicitly. - Using
any(interface{}) for ordinary parameters: Throws away compile-time type safety; reach for a small interface or a constrained generic instead.
💡 Tip
Look at Go's standard library for inspiration: io.Reader, io.Writer, fmt.Stringer, error, and http.Handler all have one method. The smaller the interface, the more useful it becomes.
What happens if you skip this step
Giant provider-side interfaces make unit tests painful to write, and one accidentally returned typed-nil pointer causes production callers to treat successful operations as crashes.
A function declares var err *ValidationError, does not assign it because validation succeeded, and ends with return err (return type error). What does if err != nil evaluate to in the caller?
About
Define small one-method interfaces, satisfy them without implements keywords, and swap real dependencies for bytes.Buffer in tests. After this, you can decouple callers from concrete types.
- Duration
- 5 min
- Last update
- 11/27/2026
Comments
Sign in to commentNo comments yet.