如何在循环中创建地图键?

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

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[&quot;{x[i]}&quot;] = 0)

package main
import &quot;fmt&quot;

func main() {
	x := [3]string{&quot;aa&quot;,&quot;bb&quot;,&quot;cc&quot;}
	
	var keyval map[string]int
	
	for i := 0; i &lt; len(x); i++ {
		keyval[&quot;{x[i]}&quot;] = 0
	}
	
	fmt.Println(keyval)
}

I tried to use keyval[&quot;x[i]&quot;] = 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

huangapple
  • 本文由 发表于 2017年6月23日 21:54:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/44723188.html
匿名

发表评论

匿名网友

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

确定