snippetgoCritical
How to join a slice of strings into a single string?
Viewed 0 times
howslicestringssinglejoinstringinto
Problem
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?
Solution
The title of your question is:
How to join a slice of strings into a single string?
but in fact,
To get an actual slice, you should write:
and then you'll find that your code for joining it works perfectly:
(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
(Try it out: https://play.golang.org/p/zy8KyC8OTuJ.)
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"}and then you'll find that your code for joining it works perfectly:
fmt.Println(strings.Join(reg, ","))(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.)
Code Snippets
reg := []string{"a", "b", "c"}fmt.Println(strings.Join(reg, ","))fmt.Println(strings.Join(reg[:], ","))Context
Stack Overflow Q#28799110, score: 288
Revisions (0)
No revisions yet.