When would you use Fmt Sprintf in a real project
Fast recall
Quick revision
Core answer
Practical understanding of Fmt Sprintf.
Repeating a definition without saying when to use it.
Give one trade-off and say how you would test it.
Interview-ready guide
Interview answer
Three verbs, three contracts, one comparison:
fmt.Sprintf("%v", "go") // go
fmt.Sprintf("%s", "go") // go
fmt.Sprintf("%q", "go") // "go" — quoted
fmt.Sprintf("%v %s %q", 'g', 'g', 'g')
// 103 g 'g' — %v: the NUMBER, %s: the character, %q: quotedExecuted. The differences that matter:
%v renders the DEFAULT form — never fails. For a rune (int32), that's the NUMBER (103). For structs, {Field Values}. For nil pointers,
%s renders the string-or-Stringer form: strings, []byte as text, anything with String() gets it called. A rune under %s shows the CHARACTER.
%q renders the SOURCE form: strings become "..." with internal quotes/escapes ESCAPED, runes become '...'. The safe verb for LOGGING UNTRUSTED DATA — a %v of input containing quotes or ANSI escapes injects into your terminal; %q neutralizes it.
When would you use Fmt Sprintf in a real project
Direct Answer
%v: default rendering of any value. %s: the string/Stringer form. %q: the value as Go SOURCE — quoted, with escapes visible. Use %v to debug, %s for text, %q to log untrusted content safely.
Deep Dive & Architecture
The rendering pipeline — the interfaces %v and %s consult: both check for Stringer (String()) and error (Error()); %s additionally handles string/[]byte natively. For values with NEITHER, %s silently falls back to %v's default — why %s on an int 'works' (42) and the difference only surfaces with runes (the int32-that-is-a-rune: %v number, %s character).
%q's implementation per kind: strings → strconv.Quote (double-quoted, escapes: ", \, \n, \xNN for non-printables); runes → strconv.QuoteRune ('g', 'é'); integers → %d (nothing to quote). 'Quote if quotable, default otherwise.' The escaping table is the security story: terminal escapes render as source form — log injection (the log4j-style newline-escape pattern) is neutralized at the verb level.
When to reach for each, one line per context: logs → %v (+%v for structs); user-visible text → %s (or direct print); log fields with untrusted content → %q (injection-proof); type debugging → %T next to %v — the standard 'what IS this' pair.
Common Mistakes & Pitfalls
Repeating a definition without saying when to use it.
Check your understanding
Answer these without looking back at the article.
- What is Fmt Sprintf, and when would you use it?
- 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.