英文:
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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论