英文:
using map[string]interface{} :
问题
给定以下代码:
type Message struct {
Params map[string]interface{} `json:"parameters"`
Result interface{} `json:"result"`
}
func (h Handler) Product(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
msg := &Message{
Params: map[string]interface{}{
"id1": val1,
"id2": val2,
},
}
h.route(msg)
}
这段代码的目的是能够将一个未知数量的 id1 => val1, id2 => val2 ... 块发送给 h.route。
它给我返回了以下错误:
在复合字面量中缺少类型
英文:
Given the following code:
type Message struct {
Params map[string]interface{} `json:"parameters"`
Result interface{} `json:"result"`
}
func (h Handler) Product(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
msg := &Message{
Action: "get_products",
Params: {
"id1": val1,
"id2": val2,
},
}
h.route(msg)
}
The idea is to be able to send a block of an unknown amount id1 => val1, id2 =>val2 ... to h.route.
it gives me this error:
> missing type in composite literal
答案1
得分: 15
你应该像这样初始化它:
func (h Handler) Product(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
msg := &Message{
Action: "get_products",
Params: map[string]interface{}{
"id1": val1,
"id2": val2,
},
}
h.route(msg)
}
简化后的编译代码:http://play.golang.org/p/bXVOwIhLlg
英文:
You should initialize it like this:
func (h Handler) Product(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
msg := &Message{
Action: "get_products",
Params: map[string]interface{}{
"id1": val1,
"id2": val2,
},
}
h.route(msg)
}
Stripped down to compile: http://play.golang.org/p/bXVOwIhLlg
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论