使用 map[string]interface{}:

huangapple go评论68阅读模式
英文:

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

huangapple
  • 本文由 发表于 2016年4月14日 23:06:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/36627096.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定