How to Join a Slice of Strings into a Single String in Go

To join a slice of strings into a single string in Go, you can use the strings.Join() function from the strings package. The strings.Join() function takes a slice of strings and a separator string as arguments and returns a single string with the elements of the slice joined by the separator.

package main

import (
  "fmt"
  "strings"
)

func main() {
  words := []string{"Krunal", "Lathiya!"}

  joined := strings.Join(words, " ")

  fmt.Println("Joined string:", joined)
}

Output

Joined string: Krunal Lathiya!

In this example, we have a slice of strings called words.

We used the strings.Join() function to join the slice elements with a space separator and store the result in the joined variable. Then, we printed the joined string.

That’s it.

Leave a Comment