我有以下代碼:package mainimport "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)}哪個不編譯我正在嘗試將其鍵作為字符串和值作為數字添加到結構作為字段但我無法訪問任何幫助的地圖?
1 回答

慕森王
TA貢獻1777條經驗 獲得超3個贊
映射類型是引用類型,如指針或切片,因此conf.B
上面的值為 nil,因為它不指向已初始化的映射。讀取時,nil 映射的行為類似于空映射,但嘗試寫入 nil 映射會導致運行時恐慌;不要那樣做。要初始化地圖,請使用內置make
函數:
conf.B = make(map[string]int)
- 1 回答
- 0 關注
- 142 瀏覽
添加回答
舉報
0/150
提交
取消