Junior — Middle
What is the most effective and safe way to insert elements into a string during a loop execution?
sobes.tech AI
Answer from AI
In Go, for efficient and safe insertion of elements into a string during a loop, it is recommended to use the strings.Builder type. It allows accumulating strings without creating many intermediate objects, which significantly improves performance and reduces garbage collector load.
Example of usage:
var builder strings.Builder
for _, elem := range elements {
builder.WriteString(elem)
builder.WriteString(",") // for example, adding a separator
}
result := builder.String()
Using concatenation with += in a loop is inefficient, as each operation creates a new string. strings.Builder works with an internal buffer and expands as needed, which is safe and fast.