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

GoSlice

Go Problem Overview


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?

Go Solutions


Solution 1 - Go

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.)

Solution 2 - Go

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.

Solution 3 - Go

This is still relevant in 2018.

To String

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

Back to Slice again

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questioncycle4passionView Question on Stackoverflow
Solution 1 - GoruakhView Answer on Stackoverflow
Solution 2 - GoDenys SéguretView Answer on Stackoverflow
Solution 3 - GoEdwinnerView Answer on Stackoverflow