Panic/error 向地图中插入值时
Panic/error while inserting a value into a map
我有以下代码:
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)
}
未编译我正在尝试添加映射,其中键为字符串,值为数字以构造为字段,但我无法访问任何帮助?
Map 类型是引用类型,如指针或切片,因此上面 conf.B
的值是 nil,因为它不指向初始化的 map。一个 nil 映射在读取时表现得像一个空映射,但尝试写入一个 nil 映射会导致运行时恐慌;不要那样做。要初始化地图,请使用内置的 make
函数:
conf.B = make(map[string]int)
我有以下代码:
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)
}
未编译我正在尝试添加映射,其中键为字符串,值为数字以构造为字段,但我无法访问任何帮助?
Map 类型是引用类型,如指针或切片,因此上面 conf.B
的值是 nil,因为它不指向初始化的 map。一个 nil 映射在读取时表现得像一个空映射,但尝试写入一个 nil 映射会导致运行时恐慌;不要那样做。要初始化地图,请使用内置的 make
函数:
conf.B = make(map[string]int)