How to Convert a Slice to String in Golang

To convert a slice to a string in Golang, you can use the “strings.Join()” function. The conversion doesn’t change the original data. The only difference between string and byte slice is that the strings are immutable, while byte slices can be modified.

package main

import (
  "fmt"
  "reflect"
  "strings"
)

func main() {
  str1 := []string{"Trump", "In", "India", "On", "Feb 25"}
  fmt.Println(str1)
  fmt.Println(reflect.TypeOf(str1))

  str2 := strings.Join(str1, " ")
  fmt.Println(str2)
  fmt.Println(reflect.TypeOf(str2))

  str3 := strings.Join(str1, ", ")
  fmt.Println(str3)
  fmt.Println(reflect.TypeOf(str3))
}

Output

[Trump In India On Feb 25]
[]string
Trump In India On Feb 25
string
Trump, In, India, On, Feb 25
string

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.