7

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

EB2127
  • 1,788
  • 3
  • 22
  • 43
  • 1
    Bad idea to use `new` as variable name. `new()` is also the [allocation](https://golang.org/ref/spec#Allocation) function. – Tim Nov 16 '21 at 16:43

2 Answers2

17

How about the following code?

commaSep := "'" + strings.Join(example, "', '") + "'"

Go Playground

phonaputer
  • 1,485
  • 4
  • 9
  • This fails with an empty slice: https://play.golang.org/p/C_KPKZAUm1e – colm.anseo Sep 09 '20 at 01:49
  • solution: `if len(example) > 0 { /* above code */ }`. Although OP didn't actually say what is correct output if the slice is empty. – phonaputer Sep 09 '20 at 02:01
  • I think if the slice is empty, pass. So, the above conditional would work. – EB2127 Sep 09 '20 at 02:49
  • Thanks for the help! I was thinking something like this, but thought perhaps there was a "better way"---I'll certainly use this – EB2127 Sep 09 '20 at 02:49
1
fmt.Sprintf("%s%s%s", "'", strings.Join(example, "', '"), "'")
droid-zilla
  • 536
  • 7
  • 8
  • 1
    This answer was reviewed in the [Low Quality Queue](https://stackoverflow.com/help/review-low-quality). Here are some guidelines for [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). Code only answers are **not considered good answers**, and are likely to be downvoted and/or deleted because they are **less useful** to a community of learners. It's only obvious to you. Explain what it does, and how it's different / **better** than existing answers. [From Review](https://stackoverflow.com/review/low-quality-posts/32419978) – IndieGameDev Aug 05 '22 at 17:45