String Concatenation
Start with String Concatenation
Concatenation combines strings into a new string. It is useful for small messages, and Go offers efficient tools when many pieces need to be assembled.
What you’ll learn
- Explain the main purpose of string concatenation.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Use + for a few strings, such as first + " " + last. For many pieces in a loop, strings.Builder avoids repeated intermediate strings and lets you write chunks using WriteString.
The builder’s String() method returns the assembled value. In simple code, choose clarity before performance optimization; for repeated concatenation of many fragments, a builder can make the intended accumulation explicit.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"fmt"
"strings"
)
func main() {
greeting := "Hello" + ", " + "Go"
var builder strings.Builder
for _, word := range []string{"Learn", "Go", "today"} {
if builder.Len() > 0 {
builder.WriteString(" ")
}
builder.WriteString(word)
}
fmt.Println(greeting)
fmt.Println(builder.String())
}
Output
Hello, Go
Learn Go todayTrace what the program does
The first expression combines three pieces into Hello, Go. The loop appends words into a builder, adding a space before every word after the first. The final string is Learn Go today.
Avoid common mistakes
- A
strings.Buildermust not be copied after its first use. - Repeated
+=in very large loops can perform unnecessary allocations; use a builder when appropriate.
Try it yourself
Add another word to the builder input and verify exactly one space separates adjacent words.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced String Concatenation in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.