英文:
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: "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.
答案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{
"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.
答案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 << 1 + i] = v
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论