How to convert a slice to a string in Go
Converting a slice of strings to a single string is pretty easy to do in Go. The
strings.Join()
method is present in the standard library for this purpose, and
its usage is shown below:
package main
import (
"fmt"
"strings"
)
func main() {
s := []string{"I", "am", "a", "special", "one"}
fmt.Println(strings.Join(s, " ")) // I am a special one
}
The first argument to the Join()
method is the slice and the second is the
delimiter which is used to separate each individual string in the result. In the
above example, a space was used as the delimiter. The code snippet below uses a
pipe delimiter with a single space on either side.
fmt.Println(strings.Join(s, " | ")) // I | am | a | special | one
If you don’t want to separate the strings with a delimiter, pass an empty string
as the second argument to Join()
.
fmt.Println(strings.Join(s, "")) // Iamaspecialone
To convert the resulting string to a string slice again, check out the strings.Split() method.
Thanks for reading, and happy coding!