How to join a slice to a string in Golang

In this shot, we’ll learn how to join a slice into a string using a separator in Golang.

We can use the Join function from the strings package to join a slice.

Syntax

strings.Join(slice, separator)

Parameters

The Join function accepts two parameters:

  1. slice: The elements that need to be converted to a string.
  2. separator: We can join a slice with separators like a space, underscore, hyphen, etc.

Return values

Join returns a new string with all the elements present in the slice.

Example

In this example, we will try to join a slice of strings into a string with _ as a separator.

Code

package main
//import format and strings package
import(
"fmt"
"strings"
)
//program executin starts here
func main(){
//Declare a slice
s := []string{"This","is","an","example"}
//Join slice into a string
snew := strings.Join(s,"_")
//display the string
fmt.Println(snew)
}

Explanation

In the code snippet above:

  • Lines 5 and 6: We import the format and strings packages.

  • Line 10: The program execution starts from the main() function in Golang.

  • Line 13: We declare and initialize the slice s, which is a collection of strings.

  • Line 16: We use the Join() function to join the slice with the _ separator.

  • Line 19: We display the string that is created from joining the slice.

Free Resources