[英]How to interpolate a byte slice?
I'm attempting to build a JSON payload for a POST request: 我正在尝试为POST请求构建JSON负载:
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: 我尝试使用%s
,但这显然在语法上是不正确的:
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. 谢谢。
To use %s
, you need a formatting function. 要使用%s
,您需要格式化功能。
var payload = []byte(fmt.Sprintf(`{"foo":%q, "hello":%q}`, val1, val2))
( %q
is like %s
but adds quotes for you) ( %q
与%s
类似,但为您添加了引号)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.