How to Concatenate Strings in Go: Simple Syntax and Examples
In Go, you can concatenate strings using the
+ operator to join two or more strings. For more efficient concatenation, especially in loops, use strings.Builder which avoids creating many intermediate strings.Syntax
Use the + operator to join strings directly. For example, str1 + str2 combines two strings. Alternatively, use strings.Builder to build strings efficiently by writing parts and then converting to a final string.
go
package main import ( "fmt" "strings" ) func main() { // Using + operator greeting := "Hello, " + "world!" fmt.Println(greeting) // Using strings.Builder var builder strings.Builder builder.WriteString("Hello, ") builder.WriteString("world!") result := builder.String() fmt.Println(result) }
Output
Hello, world!
Hello, world!
Example
This example shows how to concatenate strings using both the + operator and strings.Builder. The + operator is simple for a few strings, while strings.Builder is better for many concatenations.
go
package main import ( "fmt" "strings" ) func main() { // Concatenate with + operator firstName := "John" lastName := "Doe" fullName := firstName + " " + lastName fmt.Println("Full name:", fullName) // Concatenate with strings.Builder var sb strings.Builder sb.WriteString("John") sb.WriteString(" ") sb.WriteString("Doe") fmt.Println("Full name using Builder:", sb.String()) }
Output
Full name: John Doe
Full name using Builder: John Doe
Common Pitfalls
A common mistake is using the + operator inside loops for many strings, which creates many temporary strings and slows down the program. Instead, use strings.Builder to improve performance. Also, remember that strings in Go are immutable, so concatenation creates new strings.
go
package main import ( "fmt" "strings" ) func main() { // Inefficient way: concatenating in a loop with + result := "" for i := 0; i < 3; i++ { result += "Go" } fmt.Println("Inefficient result:", result) // Efficient way: using strings.Builder var builder strings.Builder for i := 0; i < 3; i++ { builder.WriteString("Go") } fmt.Println("Efficient result:", builder.String()) }
Output
Inefficient result: GoGoGo
Efficient result: GoGoGo
Quick Reference
Here is a quick summary of string concatenation methods in Go:
| Method | Usage | Best For |
|---|---|---|
| + operator | str1 + str2 | Few strings, simple cases |
| strings.Builder | builder.WriteString(str) | Many strings, loops, performance |
| fmt.Sprintf | fmt.Sprintf("%s%s", str1, str2) | Formatted strings, readability |
Key Takeaways
Use the + operator for simple and few string concatenations.
Use strings.Builder for efficient concatenation in loops or many strings.
Strings in Go are immutable; concatenation creates new strings.
Avoid using + operator repeatedly in loops to prevent performance issues.
fmt.Sprintf can also concatenate strings with formatting.