go - 如何插入 byte slice ?

标签 go

我正在尝试为 POST 请求构建 JSON 负载:

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

但是,我希望从现有字符串中插入值。我试过使用 %s,但这显然在语法上不正确:

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

感觉我正在以完全错误的方式解决这个问题。任何建议,将不胜感激。谢谢。

最佳答案

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

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

(%q 类似于 %s 但会为您添加引号)

关于go - 如何插入 byte slice ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30946869/

相关文章:

docker - Go:在声明性Jenkinsfile中找不到

Go:一个生产者多个消费者

go - 为什么 Go 有一个 "bit clear (AND NOT)"运算符?

gorename 在 VS Code 中失败,没有明确的错误

mongodb - 如何导入官方mongodb驱动包

go - 如何获取第二天的具体时间

makefile - go test 在 Makefile 中找不到包测试

运行时崩溃

database - 我是否需要对存储在数据库中的刷新 token 进行哈希处理?

string - 戈朗 : print string array in an unique way