如何制作一个只使用一组键的地图

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

How to make map to use only a set of keys

问题

我想创建一个只能包含预定义键的映射。例如:

set of values be like "todo", "inprogress", "done"

map[set]interface{}

我可以考虑使用结构体来实现,但这样会很繁琐。在这里还有其他可以使用的方法吗?

英文:

I want to create a map which can only have predefined keys.
for example

set of values be like "todo", "inprogress","done"

map[set]interface{}

I can think of struct will be helpful here but it will be very tedious.

Is there anything else we can use here?

答案1

得分: 2

你基本上有两个选择:

  1. 使用结构体。
  2. 对映射进行验证。

如果你愿意,使用setter方法可能会更容易实现选项2。但从根本上讲,你必须验证键是否与你的预期相匹配。

英文:

You have basically two options:

  1. Use a struct.
  2. Perform validation on the map.

#2 may be made easier with the use of a setter method, if you wish. But fundamentally, you must validate that the keys present (or added) to match your expectations.

huangapple
  • 本文由 发表于 2021年5月25日 15:02:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/67683173.html
匿名

发表评论

匿名网友

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

确定