Golang Join Examples (strings.Join)

Use the Join method to merge together a string slice with a delimiter in between each string.

Join. This method combines a slice of strings into a single string. We pass it the slice as the first argument. The delimiter to be inserted is the second.SliceStrings

Notes, join. With join we must pass 2 arguments. To join with no delimiter (convert a string slice to a string) we can use an empty string as the delimiter. This works well.

First example. Here we create an empty string slice and then append 3 strings. We join those strings together with ellipses. The Join() func in Go is like those in many other languages.
Golang program that uses Join package main import ( "fmt" "strings" ) func main() { // Create a slice and append three strings to it. values := []string{} values = append(values, "cat") values = append(values, "dog") values = append(values, "bird") // Join three strings into one. result := strings.Join(values, "...") fmt.Println(result) } Output cat...dog...bird

No delimiter. Suppose we have a slice of strings, and each string is the same length. We can join these strings together and then extract them based on their length alone.
So: No delimiter is needed. We can join with an empty string. This creates the most compact string representation possible.
Golang program that joins with no delimiter package main import ( "fmt" "strings" ) func main() { // A slice of 3 strings. values := []string{"a", "b", "c"} // Join with no separator to create a compact string. joined := strings.Join(values, "") fmt.Println(joined) } Output abc

A review. When we join a slice together, we some information about the individual strings. Data loss can occur if we have a delimiter inside one of the strings. This must be tested for.

© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.