英文:
How to create map keys in a loop?
问题
我按照教材的要求进行操作,但是出现了错误。
错误信息为:panic: 在 nil map 中进行赋值操作(位于第 keyval["{x[i]}"] = 0
行)
package main
import "fmt"
func main() {
x := [3]string{"aa","bb","cc"}
var keyval map[string]int
for i := 0; i < len(x); i++ {
keyval["{x[i]}"] = 0
}
fmt.Println(keyval)
}
我尝试使用 keyval["x[i]"] = 0
,但效果是一样的。
英文:
I do according to the textbook, but there is an error
panic: assignment to entry in nil map (in line keyval["{x[i]}"] = 0
)
package main
import "fmt"
func main() {
x := [3]string{"aa","bb","cc"}
var keyval map[string]int
for i := 0; i < len(x); i++ {
keyval["{x[i]}"] = 0
}
fmt.Println(keyval)
}
I tried to use keyval["x[i]"] = 0
but the effect is the same
答案1
得分: 6
你必须先初始化你的映射:
keyval := make(map[string]int)
根据这篇博客文章:
映射类型是引用类型,就像指针或切片一样,所以上面的
m
的值是nil
;它没有指向一个初始化的映射。
在这里运行Go代码:
https://play.golang.org/p/2JuPS1J7KK
编辑以回答问题者的后续问题。如果你想使用切片中的字符串作为映射的键,你需要进行额外的更改:
keyval[x[i]] = 0
在这里运行Go代码:
https://play.golang.org/p/feMSwvbEGS
英文:
You must first initialize your map:
keyval := make(map[string]int)
According to this blog post:
> Map types are reference types, like pointers or slices, and so the
> value of m above is nil; it doesn't point to an initialized map.
GoPlay here:
https://play.golang.org/p/2JuPS1J7KK
Edit to answer OP's followup. If you're looking to use the strings from your slice as the key to the map, you need to make an additional change:
keyval[x[i]] = 0
GoPlay here:
https://play.golang.org/p/feMSwvbEGS
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论