英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论