typestar

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

  1. strings.Builder grows one buffer and writes into it.
  2. Grow preallocates when you know the size.
  3. strings.Join is simpler when you already have the parts.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 5 in Strings & formatting, step 27 of 30 in Language basics.

← Previous Next →

Building strings in other languages