Go – String Concatenation

To concatenate strings in Go programming, we can use strings.Join() function.

The syntax of strings.Join() function is:

strings.Join(a []string, sep string)

where a is a string array and sep string is used between the joins of adjacent strings.

Examples

In the following program, we will take two strings and concatenate them using Join() function, with single space as a separator.

example.go

package main

import (
	"fmt"
	"strings"
)

func main() {
	var str1 = "Hello"
	var str2 = "World"
	var output = strings.Join([]string{str1, str2}, " ")
	fmt.Println(output)
}

Output

Hello World

In the following program, we have taken four strings in an a string array and joined them with the separator: comma ,.

example.go

package main

import (
	"fmt"
	"strings"
)

func main() {
	var a = []string{"US", "Canada", "Europe", "Australia"}
	var sep = ","
	var output = strings.Join(a, sep)
	fmt.Println(output)
}

Output

US,Canada,Europe,Australia
ADVERTISEMENT

Conclusion

In this Golang Tutorial, we learned how to concatenate strings using Join() function.