Join
This Go 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.
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.
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.
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)
}cat...dog...bird
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.
string
. This creates the most compact string
representation possible.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)
}abc
When we join a slice together, we lose 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.