将值插入地图时出现恐慌/错误

时间:2020-01-28 19:55:02

标签: dictionary go initialization panic

我有以下代码:

package main
import "fmt"

type config struct {
    user    string
    pass    string
    B       map[string]int 
}

func main() {
    conf := new(config)
    conf.user = "florence"
    conf.pass = "machine"
    //  trying to fill a map entry "x" where the value is 2 but the compiler throws an error
    conf.B["x"]=2

    fmt.Printf("%+v", conf)
}

未编译的我正在尝试添加映射,其键为字符串,值为数字,以struct作为字段,但是我无法访问任何帮助?

1 个答案:

答案 0 :(得分:0)

映射类型是引用类型,例如指针或切片,因此上面的conf.B的值为nil,因为它没有指向已初始化的映射。读取时,nil映射的行为类似于空映射,但是尝试写入nil映射将导致运行时恐慌。不要那样做。要初始化地图,请使用内置的make函数:

conf.B = make(map[string]int)