How to Convert a Slice to a String in Go
The Go standard library provides the strings.Join()
method for efficiently
concatenating the elements of a string slice into a single string, using a
specified delimiter. Below is an example of how to use it:
package main
import (
"fmt"
"strings"
)
func main() {
s := []string{"I", "am", "a", "special", "one"}
fmt.Println(strings.Join(s, " ")) // I am a special one
}
In strings.Join()
, the first parameter is the slice of strings, and the second
is the delimiter. The function combines the elements of the slice into a single
string, inserting the delimiter between each element. In the example above, a
space is used as the delimiter. However, you can use any string as a delimiter,
such as a pipe with spaces:
fmt.Println(strings.Join(s, " | ")) // I | am | a | special | one
For cases where you don’t require any separation between the strings, simply pass an empty string as the delimiter:
fmt.Println(strings.Join(s, "")) // Iamaspecialone
And if you need to revert back from a single string to a slice of strings,
strings.Split()
is the function to use.
Thanks for reading, and happy coding!