Fmt.errorf With %w Do
Fast recall
Quick revision
Core answer
Whether you understand Fmt Errorf beyond memorized syntax.
Giving a definition without explaining a practical trade-off.
Connect the concept to a small production example and state its complexity or failure mode.
Interview-ready guide
Interview answer
%w is the wrap verb. It builds a new error whose message is your formatted text with the wrapped error's message embedded, AND records the wrapped error as unwrap-able:
base := errors.New("disk full")
wrapped := fmt.Errorf("write config: %w", base)
// prints: write config: disk full
// AND: errors.Is(wrapped, base) == true — the chain is intactThat second property is the whole point. Any caller can ask 'was the underlying cause disk full?' and get the right answer, no matter how many layers wrapped it. Without %w — with %v — the message would print the same, but the causal link would be severed: the chain is data the error carries, not text.
Fmt.errorf With %w Do
Direct Answer
Creates an error that wraps another error — adding your message while keeping errors.Is/As working through the chain.
Deep Dive & Architecture
Mechanically, %w tells fmt.Errorf to store the wrapped error in the returned error's internal tree (an fmt.wrapError holding both your format result and the cause). The errors package's Is and As walk that tree via Unwrap: each %w is an edge, and Is/As traverse edges until they find a match or exhaust the chain.
The walk semantics are the interview-grade detail:
- errors.Is(e, target) — walks the chain, comparing each node to target (identity or the target's Is method). True if the cause is anywhere below.
- errors.As(e, &typedTarget) — walks until it finds an error assignable to the type, then copies it into your target.
- Both treat the chain as read-only evidence: they never unwrap past a %v (there's no edge to follow).
The composed behavior — wrap at every layer with %w, inspect with Is/As at the boundary — is Go's answer to exception type-matching, but with the chain explicit in the data rather than in a type hierarchy.
Common Mistakes & Pitfalls
Giving a definition without explaining a practical trade-off.
Check your understanding
Answer these without looking back at the article.
- When would you use Fmt Errorf in a real project?
- How would you compare Fmt Errorf with an alternative?
- What is a common mistake when using Fmt Errorf?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.