Fmt Sprintf
Fast recall
Quick revision
Core answer
Whether you understand Fmt Sprintf 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
Sprintf builds a string from a format and arguments:
name, age := "Al", 30
s := fmt.Sprintf("Hi %s, you are %d", name, age)
// "Hi Al, you are 30"The verbs worth knowing cold:
- %s — strings (and Stringers)
- %d — integers
- %f — floats (%.2f for precision)
- %v — default format for ANY value — always works
- %q — quoted Go syntax: strings get "go"
- %T — the TYPE — debugging gold
- %x — hex
fmt.Sprintf("%q %x %v", "go", 255, []int{1,2})
// "go" ff [1 2] — executed%v is the safety verb — never fails to render SOMETHING (structs as {a b c}, nil as
The family: Sprintf → string. Printf → stdout. Fprintf → any io.Writer (files, buffers, network). Errorf → an error (different family, same verbs — the %w special case lives there).
Fmt Sprintf
Direct Answer
fmt.Sprintf(format, args...) returns a formatted string: %s strings, %d ints, %f floats, %v anything (the always-works verb), %q quoted, %T type. Sprintf→string, Printf→stdout, Fprintf→any Writer.
Deep Dive & Architecture
The format mini-language beyond verbs — the interview follow-up: %10s pads width 10 (right-aligned), %-10s left, %08d zero-pads, %.2f float precision, % x spaces hex bytes. Width and precision are the two numbers; flags are letters.
The %v family: %+v adds field NAMES ({Name:Al Age:30} — the debugging upgrade), %#v prints Go-source representation (map[string]int{"a":1} — copy-pasteable). Three detail levels, one character apart.
The performance contract: Sprintf parses the format at RUNTIME every call — reflection over args, verb dispatch. ~3-5x an Itoa path, allocation-heavy — fine for UI/errors, wrong in hot loops. The escapes: strconv (no format parsing), plain concatenation for fixed shapes, Builder for accumulation. If it's in a loop or request path, measure — Sprintf is usually the first flag.
Errorf's special case: %w is a WRAP directive (fmt.Errorf("ctx: %w", err) chains the error) — Sprintf and Errorf share the mini-language, diverge on that one verb. Knowing the divergence is depth.
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 Sprintf in a real project?
- How would you compare Fmt Sprintf with an alternative?
- What is a common mistake when using Fmt Sprintf?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.