Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add single-quotes to strings in Golang?

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

like image 316
EB2127 Avatar asked Dec 10 '22 00:12

EB2127


2 Answers

How about the following code?

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

Go Playground

like image 106
phonaputer Avatar answered Jan 02 '23 18:01

phonaputer


fmt.Sprintf("%s%s%s", "'", strings.Join(example, "', '"), "'")
like image 24
droid-zilla Avatar answered Jan 02 '23 17:01

droid-zilla