String construction
Use the simplest string-building tool that matches the job: `+` for small local cases, `fmt.Sprintf` for formatting, and `strings.Builder` for piecemeal assembly.
Canonical guidance
- use
+for a few local concatenations - use
fmt.Sprintfwhen formatting is the point - use
strings.Builderwhen assembling a string incrementally over several writes
Use when
- formatting messages
- generating text output
- reviewing small performance-sensitive string assembly
Avoid
- introducing
strings.Builderfor tiny fixed expressions - using
fmt.Sprintfwhen simple concatenation is clearer - premature micro-optimization without a readability or measurement win
Preferred pattern
var b strings.Builder
b.WriteString(prefix)
b.WriteString(name)
return b.String()
Anti-pattern
- replacing every short
a + bwith a builder purely because it feels more performance-minded
Explanation: This is tempting because builders sound efficient, but for small local cases they often add ceremony without helping clarity.
Why
- Google’s best-practice guidance is unusually concrete here and fills a gap in the current corpus
Related pages
Sources
- Google Go Best Practices - Google