Sobes.tech
Junior — Middle

How can multiple string values be quickly and efficiently combined in a program?

sobes.tech AI

Answer from AI

In Go, for efficient concatenation of multiple strings, it is better to use the strings.Builder type. It allows accumulating strings without creating many intermediate objects, which is significantly faster than concatenation using the + operator in a loop.

Example of using strings.Builder:

package main

import (
    "fmt"
    "strings"
)

func main() {
    var builder strings.Builder
    parts := []string{"Hello", " ", "World", "!"}

    for _, part := range parts {
        builder.WriteString(part)
    }

    result := builder.String()
    fmt.Println(result) // Output: Hello World!
}

This approach saves memory and improves performance when working with a large number of strings.