How to Convert Golang Slice to String

A slice is the data structure describing the contiguous section of an array stored separately from the slice variable itself. A slice is not an array. Instead, a slice represents a piece of an array.

When you convert between the string and a byte slice (array), you get a new slice that contains the same bytes as a string and vice versa.

Golang slice to string

To convert a slice to a string in Golang, use the string Join() function. The string Join() is a built-in Go function that converts slice to string.

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.

To modify the characters (runes) of the string, you may want to convert the string to a rune slice instead.

Example of String slice to string

See the following code.

// hello.go

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

go run hello.go
[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. So, Golang string.Join() function that converts slice to string. We have passed the space(” “) as a delimiter. So we will join the slice elements by space.

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

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

Then we used the Golang string.Join() function again, but we have passed (,) Comma this time. So, command-separated values will be returned, a type of string.

So, if you want to get CSV values in Golang, then you can use the Go string.Join() method.

Conclusion

You can convert Golang “type []string” to string using string.Join() function, which takes two parameters.

  1. Slice
  2. Delimiter

It returns a string.

Golang Join(slice, sep) function concatenates the items of its first argument to create a single string. Then, the separator string sep is placed between items in the resulting string.

Leave a Comment

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