How to Efficiently Concatenate Strings in Go


If you are using a version of Go >= 1.10, then you should be using the newer strings.Builder pattern as follows:

package main
import (
    "strings"
    "fmt"
)
func main() {
    var sb strings.Builder
    for i := 0; i < 100; i++ {
        sb.WriteString("a")
    }
    fmt.Println(sb.String())
}

For older version, you should be looking to use the bytes.Buffer instead:

package main
import (
    "bytes"
    "fmt"
)
func main() {
    var buffer bytes.Buffer
    for i := 0; i < 100; i++ {
        buffer.WriteString("a")
    }
    fmt.Println(buffer.String())
}