-1

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?

Shubham Chadokar
  • 2,520
  • 1
  • 24
  • 45
  • 1
    Why would a struct be tedious? – Jonathan Hall May 25 '21 at 07:10
  • See related: [Creating a Constant Type and Restricting the Type's Values](https://stackoverflow.com/questions/37385007/creating-a-constant-type-and-restricting-the-types-values/37386119#37386119) – icza May 25 '21 at 07:29
  • @Flimzy this is a map because _any_ value of bool can be used as the map key. (The fact that there aren't that many different bools in Go doesn't matter here) Whereas the original question talked about string keys. – Volker May 25 '21 at 07:50
  • @Volker: The OP appears to be (or at least may as well be) asking about an enum, represtened as strings. I don't see any fundamental difference between an enum and any other data type with a "small number" of possible values. – Jonathan Hall May 25 '21 at 07:51
  • @Flimzy `set = {"todo", "inprogress","done"}` doesn't look like an enum or a data type but a set of strings. Let's agree the OP is unclear and just should use a struct. – Volker May 25 '21 at 09:33
  • @Volker I updated the question. Basically the set meant for example, like only this set of values. It was not related to go syntax. – Shubham Chadokar May 27 '21 at 04:40

1 Answers1

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.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189