Iota to define keys on a Go map?

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

Iota to define keys on a Go map?

问题

让我们假设我们有一个 map[int]string,我们想要像这样定义它:

var a map[int]string =  {
 1: "some"
 3: "value"
 4: "maintained"
 7: "manually"
 // 更多的100个条目...
}

我想手动维护值,因为它们没有模式,但是键有。是否有一种像使用 1 << 1 + iota 定义枚举值那样维护键列表的方法?

我不是在问是否可以将 iota 用作映射键(很遗憾,据我所知是不行的),只是是否有一种同样优雅的方法来创建定义好的键序列。

英文:

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

var a map[int]string =  {
 1: &quot;some&quot;
 3: &quot;value&quot;
 4: &quot;maintained&quot;
 7: &quot;manually&quot;
 // 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 &lt;&lt; 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.

答案1

得分: 3

你最好的选择是将有序的值存储为一个切片,然后使用一个init函数来生成这样的映射:

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
}

Go Playground上运行它。

你可以根据需要更改idxToKey函数的转换方式。在这个例子中,我使用了你给出的转换方式,但它可以是任何内容。参数的位置与通常放置iota关键字的位置相同。

英文:

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{
    &quot;some&quot;,
    &quot;value&quot;,
    &quot;maintained&quot;,
    &quot;manually&quot;,
}

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

func idxToKey(i int) int {
	return 1&lt;&lt;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.

答案2

得分: 1

一种方法是创建一个包含所有单词的数组/切片,并通过循环遍历,类似于以下代码:

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

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

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 &lt;&lt; 1 + i] = v
}

huangapple
  • 本文由 发表于 2014年12月7日 12:01:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/27339460.html
匿名

发表评论

匿名网友

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

确定