英文:
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
你基本上有两个选择:
- 使用结构体。
- 对映射进行验证。
如果你愿意,使用setter方法可能会更容易实现选项2。但从根本上讲,你必须验证键是否与你的预期相匹配。
英文:
You have basically two options:
- Use a struct.
- 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论