How to Convert a String to a Slice in Go

In Go, the standard library offers the strings.Split() function for splitting a single string into a slice of substrings based on a specified separator. Here’s an example to illustrate its usage:

go
package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "I am a special one"
	fmt.Println(strings.Split(str, " ")) // ["I", "am", "a", "special", "one"]
}

In strings.Split(), the first parameter is the string to be split, and the second parameter is the delimiter or separator. The function splits the string into a slice, with each element being a substring separated by the delimiter. If the separator is not found in the string, the result is a slice containing the original string as its only element:

go
fmt.Println(strings.Split(str, ",")) // ["I am a special one"]

For the reverse operation—combining a slice of strings into a single string—strings.Join() is the complementary function to consider.

Thanks for reading, and happy coding!