如何对字节切片进行插值?

huangapple go评论85阅读模式
英文:

How to interpolate a byte slice?

问题

我正在尝试构建一个用于POST请求的JSON负载:

var payload = []byte(`{"foo":"bar", "hello":"world"}`)

然而,我希望值能够从现有字符串中插值。我尝试使用%s,但这显然不是语法正确的:

var payload = []byte(`{"foo":%s, "hello":%s}`, val1, val2)

感觉我完全走错了方向。任何建议都将不胜感激。谢谢。

英文:

I'm attempting to build a JSON payload for a POST request:

var payload = []byte(`{"foo":"bar", "hello":"world"}`)

However, I would like the values to be interpolated from an existing string. I've tried to use %s, but this is obviously not syntactically correct:

var payload = []byte(`{"foo":%s, "hello":%s}`, val1, val2)

Feels like I'm going about this the entirely wrong way. Any suggestions would be appreciated. Thanks.

答案1

得分: 5

要使用%s,你需要一个格式化函数。

var payload = []byte(fmt.Sprintf(`{"foo":%q, "hello":%q}`, val1, val2))

%q类似于%s,但会为你添加引号)

英文:

To use %s, you need a formatting function.

var payload = []byte(fmt.Sprintf(`{"foo":%q, "hello":%q}`, val1, val2))

(%q is like %s but adds quotes for you)

huangapple
  • 本文由 发表于 2015年6月20日 04:35:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/30946869.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定