Iota to define keys on a Go map?

2.6k views Asked by At

Let's suppose we have a map[int]string and we want to define it like this:

var a map[int]string =  {
 1: "some"
 3: "value"
 4: "maintained"
 7: "manually"
 // more 100 entries...
}

I would like to maintain the values manually because they have no pattern, but the keys have. Is there a way to maintain the key list just like we do with enum values using 1 << 1 + iota?

I'm not asking if it's possible to use iota as a map key (unfortunately it's not AFAIK), just if there is an equally elegant way to create the keys on a defined sequence.

2

There are 2 answers

3
joshlf On BEST ANSWER

Your best bet is to store the ordered values as a slice, and then use an init function to generate the map like this:

var a map[int]string
var vals = []string{
    "some",
    "value",
    "maintained",
    "manually",
}

func init() {
    a = make(map[int]string)
    for idx, val := range vals {
        a[idxToKey(idx)] = val
    }
}

func idxToKey(i int) int {
    return 1<<1 + i
}

Run it on the Go Playground.

You can change idxToKey to be whatever transformation you want. I've used the one you gave in this case, but it could be anything. The argument goes where you'd normally put the iota keyword.

0
Simba On

One way would be have an array/slice of all the words and loop through similar to this;

var words []string
var a map[int]string

for i, v := range words {
   a[1 << 1 + i] = v
}