在RESTful API中使用Golang的结构体(structs)或映射(maps)

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

golang structs or maps in RESTFUL API

问题

在使用Golang创建Web服务器时,将JSON数据表示为MAP还是STRUCT是否有特定原因?还是这个决定完全基于用户的偏好?

英文:

When creating a webserver in golang, is there any specific reason why JSON data would be represented as a MAP over a STRUCT or vice versa? ..or is this decision based purely on user preference ?

答案1

得分: 2

我认为这个讨论可以有两种观点,但使用结构体和使用映射的优势在于,结构体可以让你对模式的外观有一个概念,而映射则使模式保持开放。

如果你使用结构体,查看代码的开发人员将清楚地知道你对API期望的参数或API响应的外观,而无需深入挖掘实现细节。另一方面,如果请求或响应是映射,他们将不得不查看实现细节以查看分配了哪些键和值。希望这可以帮到你!

英文:

I think this discussion could go either way but the advantages of using structs vs maps are that structs give you an idea of how the schema should look like whereas a map leaves the schema open-ended.

If you use structs, developers who look at the code will have a clear idea of what parameters you're expecting for the API or how the response of the API may look like without digging further into implementation detail. On the other hand if the requests or responses were maps, they would have to look at the implementation detail to see what keys and values are being assigned. Hope this helps!

huangapple
  • 本文由 发表于 2015年10月12日 08:06:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/33071486.html
匿名

发表评论

匿名网友

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

确定