【发布时间】:2020-08-13 08:35:12
【问题描述】:
输入:
// a slice of type string.
data := []string{"one", "two", "three"}
预期输出:
["one","two","three"]
我尝试使用这些格式说明符 https://play.golang.org/p/zBcFAh7YoVn
fmt.Printf("%+q\n", data)
fmt.Printf("%#q\n", data)
fmt.Printf("%q\n", data)
// using strings.Join()
result := strings.Join(data, ",")
fmt.Println(result)
输出: 所有值都没有逗号,
["one" "two" "three"]
[`one` `two` `three`]
["one" "two" "three"]
one,two,three
【问题讨论】:
-
你不能用 fmt.Sprintf 做到这一点,无论你使用什么动词和修饰语。如果要生成 JSON:使用 encoding/json.Marshal。如果不需要引用:通过
["+ strings.Join(data,",") +"]自己构造字符串。如果需要引用:写一个循环。