Building strings in Go
Concatenating in a loop allocates every time; a Builder does not.
func build(parts []string) (string, string) {
var b strings.Builder
b.Grow(64)
for i, part := range parts {
if i > 0 {
b.WriteString(" > ")
}
b.WriteString(part)
}
joined := strings.Join(parts, " > ")
return b.String(), joined
}
How it works
strings.Buildergrows one buffer and writes into it.Growpreallocates when you know the size.strings.Joinis simpler when you already have the parts.
Keywords and builtins used here
forfuncifrangereturnstringvar
The run, in numbers
- Lines
- 13
- Characters to type
- 229
- Tokens
- 71
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 45 seconds.
Step 3 of 5 in Strings & formatting, step 27 of 30 in Language basics.