How to join a slice of strings into a single string in Go

Created
Modified

Using strings.Join Function

Converting a slice of strings to a single string is pretty easy to do in Go. The strings.Join() method is present in the standard library for this purpose, and its usage is shown below:

package main

import (
  "fmt"
  "strings"
)

func main() {

  a := []string{"United States", "Japan", "Germany"}

  // func Join(elems []string, sep string) string
  s := strings.Join(a, ",")
  fmt.Println(s)
}
United States,Japan,Germany

Join concatenates the elements of its first argument to create a single string. The separator string sep is placed between elements in the resulting string.

Other types

For slices with ints, or other types of elements, we can first convert a slice into a string slice. For example,

package main

import (
  "fmt"
  "strconv"
  "strings"
)

func main() {

  // ints
  a := []int{1, 2, 3}

  slice := []string{}
  for _, v := range a {
    text := strconv.Itoa(v)
    slice = append(slice, text)
  }

  // func Join(elems []string, sep string) string
  s := strings.Join(slice, "|")
  fmt.Println(s)
}
1|2|3

The Go blog about the differences between slices and arrays

Related Tags