使用map [string] interface {}:

时间:2016-04-14 15:06:24

标签: dictionary go 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{
        Action: "get_products",
        Params: {
            "id1": val1,
            "id2": val2,
        },
    }
     h.route(msg)

}

这个想法是能够发送一个未知数量的块id1 => val1,id2 => val2 ...到h.route。

它给了我这个错误:

  

复合文字中缺少类型

1 个答案:

答案 0 :(得分:10)

你应该像这样初始化它:

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