[go] How to join a slice of strings into a single string?

package main

import (
"fmt"
"strings"
)

func main() {
reg := [...]string {"a","b","c"}
fmt.Println(strings.Join(reg,","))
}

gives me an error of:

prog.go:10: cannot use reg (type [3]string) as type []string in argument to strings.Join

Is there a more direct/better way than looping and adding to a var?

This question is related to go slice

The answer is


Use a slice, not an arrray. Just create it using

reg := []string {"a","b","c"}

An alternative would have been to convert your array to a slice when joining :

fmt.Println(strings.Join(reg[:],","))

Read the Go blog about the differences between slices and arrays.


This is still relevant in 2018.

To String

import strings
stringFiles := strings.Join(fileSlice[:], ",")

Back to Slice again

import strings
fileSlice := strings.Split(stringFiles, ",")