Junior — Middle
What methods can you use to concatenate strings in programming?
sobes.tech AI
Answer from AI
In Go, strings can be concatenated in several ways:
- Operator + — a simple method for a small number of strings:
s := "Hello, " + "world!"
- strings.Join function — efficient for concatenating a slice of strings with a separator:
import "strings"
words := []string{"Go", "is", "awesome"}
result := strings.Join(words, " ") // "Go is awesome"
- bytes.Buffer — useful when concatenating many strings to avoid creating multiple temporary strings:
import (
"bytes"
)
var buffer bytes.Buffer
buffer.WriteString("Hello")
buffer.WriteString(", ")
buffer.WriteString("world!")
result := buffer.String()
- strings.Builder (from Go 1.10) — a more convenient and efficient way to build strings:
import "strings"
var builder strings.Builder
builder.WriteString("Hello")
builder.WriteString(", ")
builder.WriteString("world!")
result := builder.String()
The choice of method depends on the task and the amount of data.