Golang 中的编组结构与映射

Jak*_*ler 0 json marshalling go

返回 JSON 结果时,使用 marshalledstructmap. 我见过一些代码使用 map 并将它们编组为 json 返回,其他代码使用编组结构返回 json 响应。

例子:

使用struct

type Response struct {
    A int `json:"a"`
    B string `json:"b"`
}

r := Response{A:1,B:"1"}
resp, _ := json.Marshal(r)
Run Code Online (Sandbox Code Playgroud)

使用map

m := map[string]interface{}{
    A: 1,
    B: "1",
}
resp, _ := json.Marshal(m)
Run Code Online (Sandbox Code Playgroud)

哪个更好?

mfa*_*has 5

我的想法是使用 Struct 更好,因为字段的类型已定义。如果您使用map,那么显然您将使用map[string]interface{},因为值会有所不同。使用接口类型化数据将分配堆内存。由于您只是返回响应,因此最好使用具有定义类型的结构来减少类型检查的运行时间。不过,性能差异并不重要。