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.
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.
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
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.
Info No delimiter is needed. We can join with an empty 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 30, 2025 (grammar).