How to Join Strings in Go with strings.Join

Use the `strings.Join` function from the standard library to concatenate a slice of strings with a specific separator.

Use the strings.Join function from the standard library to concatenate a slice of strings with a specific separator. It is the most efficient and idiomatic way to join strings in Go, avoiding the performance pitfalls of repeated string concatenation in loops.

Here is a basic example joining a slice of words with a space separator:

package main

import (
	"fmt"
	"strings"
)

func main() {
	words := []string{"Hello", "world", "from", "Go"}
	result := strings.Join(words, " ")
	fmt.Println(result) // Output: Hello world from Go
}

If you need to join strings with a newline or handle empty slices, strings.Join handles those cases gracefully. An empty separator results in direct concatenation, and an empty slice returns an empty string.

package main

import (
	"fmt"
	"strings"
)

func main() {
	lines := []string{"Line 1", "Line 2", "Line 3"}
	// Join with newlines
	output := strings.Join(lines, "\n")
	fmt.Println(output)

	// Join with empty separator (concatenation)
	tags := []string{"go", "backend", "api"}
	combined := strings.Join(tags, "")
	fmt.Println(combined) // Output: gobackendapi

	// Empty slice returns empty string
	empty := []string{}
	fmt.Println(len(strings.Join(empty, ","))) // Output: 0
}

Avoid manually looping and appending to a string variable, as strings are immutable in Go. That approach creates a new string object on every iteration, leading to O(n²) time complexity. strings.Join calculates the final size upfront and performs a single allocation, resulting in O(n) performance.

If you need to join strings with a custom format (e.g., adding quotes around each element), you should transform the slice first or use fmt.Sprintf for simple cases, but strings.Join remains the standard for pure concatenation with separators.