Golang 中的 Marshalling Struct 与 Map

Marshalling Struct vs Map in Golang

当 returning JSON 的结果时,使用编组 structmap,哪个在性能或最佳实践方面更好。我见过一些代码使用 map 并将它们编组为 returned 作为 json,其他代码使用编组结构来 return json 响应。

示例:

使用struct:

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

r := Response{A:1,B:"1"}
resp, _ := json.Marshal(r)

使用map:

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

哪个更好?

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