How to Join a Slice of Strings in Go with strings.Join
strings.Join(elems, sep) turns a slice of strings into one string, with sep between the items: strings.Join([]string{"a", "b"}, ", ") is "a, b". A single item comes back unchanged, and an empty slice gives an empty string.
Syntax
<text> := strings.Join(<elems>, <sep>)
| Part | What it does |
|---|---|
<elems> | The slice of strings to join. |
<sep> | The text to put between the items, such as ", ". |
<text> | The joined string. |
The strings package documentation: "Join concatenates the elements of its first argument to create a single string. The separator string sep is placed between elements in the resulting string."
The Example
The example joins two audience URLs with a comma and then with a bar, joins a slice with one item, and prints the length of the result of joining an empty slice.
Prerequisites
- Go. This guide uses Go 1.27.4.
Step 1: Write the Code
Create a file named main.go:

package main
import (
"fmt"
"strings"
)
func main() {
audiences := []string{"https://photos.example.org", "https://videos.example.org"}
fmt.Println(strings.Join(audiences, ", "))
fmt.Println(strings.Join(audiences, " | "))
fmt.Println(strings.Join([]string{"only one"}, ", "))
fmt.Println(len(strings.Join([]string{}, ", ")))
}
Step 2: Run It
go run main.go
https://photos.example.org, https://videos.example.org
https://photos.example.org | https://videos.example.org
only one
0

The command is the same in zsh, bash and PowerShell.
What Happened
- The separator went only between the items, never before the first or after the last.
- Any text works as a separator, such as
" | ". - A single item came back unchanged, with no separator.
- An empty slice gave an empty string, which is why its length printed
0.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Joining with + in a loop | You have to handle the separator for the first or last item yourself | Use strings.Join |
| Passing a slice of numbers | strings.Join only takes a []string, so it doesn't compile | Convert each number to a string first |
| Expecting brackets around the result | strings.Join adds only the separator | Add any brackets yourself |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
cannot use ... as []string value in argument to strings.Join | The slice holds something other than strings | Convert its items to strings |
undefined: strings | The strings package isn't imported | Add "strings" to the imports |
FAQ
How do I split the string back into a slice?
Use strings.Split(text, sep) with the same separator.
Does strings.Join change the slice?
No. It returns a new string and leaves the slice as it was.
Conclusion
strings.Join(elems, sep) joins a slice of strings with a separator between the items, and handles the one-item and empty cases for you.
Additional Resources
- strings.Join, in the Go standard library documentation.
