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.

Example

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

In the above code, first, we have defined a slice of string and then used the reflect package to determine the data type of the slice.

We have imported the “strings” module with strings.Join() method, and we combine all elements of a string slice into a string.

The delimiter is the second argument to “strings.Join()”. For no delimiter, please use an empty string literal.

We again used the “TypeOf()” function to check the data type in the next step.

Then, we used the strings.Join() function again, but we have passed the (,) comma this time. So, comma-separated values will be returned, which is a type of string.

Leave a Comment

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