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:
slice: The elements that need to be converted to a string.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 packageimport("fmt""strings")//program executin starts herefunc main(){//Declare a slices := []string{"This","is","an","example"}//Join slice into a stringsnew := strings.Join(s,"_")//display the stringfmt.Println(snew)}
Explanation
In the code snippet above:
-
Lines 5 and 6: We import the
formatandstringspackages. -
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.