Perhaps this is an easy question, but I haven't figured out how to do this:
I have a string slice in Go, which I would like to represent as a comma-separated string. Here is the slice example
:
example := []string{"apple", "Bear", "kitty"}
And I would like to represent this as a comma-separated string with single-quotes, i.e.
'apple', 'Bear', 'kitty'
I cannot figure out how to do this efficiently in Go.
For instance, strings.Join()
gives a comma-separated string:
commaSep := strings.Join(example, ", ")
fmt.Println(commaSep)
// outputs: apple, Bear, kitty
Close, but not what I need. I also know how to add double-quotes with strconv
, i.e.
new := []string{}
for _, v := range foobar{
v = strconv.Quote(v)
new = append(new, v)
}
commaSepNew := strings.Join(new, ", ")
fmt.Println(commaSepNew)
// outputs: "apple", "Bear", "kitty"
Again, not quite what I want.
How do I output the string 'apple', 'Bear', 'kitty'
?
How about the following code?
commaSep := "'" + strings.Join(example, "', '") + "'"
Go Playground
fmt.Sprintf("%s%s%s", "'", strings.Join(example, "', '"), "'")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With