226
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?

1
  • 5
    Why not just use reg := []string {"a","b","c"}?
    – Sean M
    Mar 1, 2015 at 21:31

3 Answers 3

263

The title of your question is:

How to join a slice of strings into a single string?

but in fact, reg is not a slice, but a length-three array. [...]string is just syntactic sugar for (in this case) [3]string.

To get an actual slice, you should write:

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

(Try it out: https://play.golang.org/p/vqU5VtDilJ.)

Incidentally, if you ever really do need to join an array of strings into a single string, you can get a slice from the array by adding [:], like so:

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

(Try it out: https://play.golang.org/p/zy8KyC8OTuJ.)

3
  • 11
    Pls, provide the working code in the answer itself, playground is a plus but not enough for acceptable answer ;-). TY!
    – shadyyx
    Mar 1, 2016 at 15:11
  • 13
    @shadyyx: I agree that the playground link is strictly supplemental; but I'm not sure what you think is missing from the answer proper. The OP's sole error was on line 10, and I provided the corrected version of that line, together with explanation. (Are you suggesting that I should have copied his/her entire example program into the answer? If so, then -- I disagree.)
    – ruakh
    Mar 1, 2016 at 16:24
  • 1
    "trying to join a slice into a string" Your solution only works for slices of strings instead of the general slice type. Sep 25, 2017 at 8:05
128

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.

0
44

This is still relevant in 2018.

To String

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

Back to Slice again

import strings
fileSlice := strings.Split(stringFiles, ",")
1
  • 2
    import "strings"
    – kspc1000
    Apr 28, 2022 at 12:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.