Junior
What happens if you add strings in Go?
sobes.tech AI
Answer from AI
In Go, string addition (+) results in concatenation. This means that the second string is added to the end of the first, creating a new string.
Example:
package main
import "fmt"
func main() {
str1 := "Hello, "
str2 := "world!"
result := str1 + str2 // Concatenation occurs
fmt.Println(result)
}
Output:
Hello, world!
Concatenation creates a new string. If you need to efficiently concatenate a large number of strings, it is recommended to use strings.Builder, which avoids creating intermediate strings.
Example with strings.Builder:
package main
import (
"fmt"
"strings"
)
func main() {
var sb strings.Builder // Declare strings.Builder
sb.WriteString("First part. ")
sb.WriteString("Second part. ")
sb.WriteString("Third part.")
result := sb.String() // Get the final string
fmt.Println(result)
}