在對map的值進行賦值操作時,如果map的值型別為struct結構體型別,那么是不能直接對struct中的欄位進行賦值的,
例如:
type T struct {
n int
}
func main(){
m := make(map[int]T)
m[0].n = 1 //map[key]struct 中 struct 是不可尋址的,所以無法直接賦值
fmt.Println(m[0].n)
}
報錯:
cannot assign to struct field m[0].n in map
原因:
- map作為一個封裝好的資料結構,由于它底層可能會由于資料擴張而進行遷移,所以拒絕直接尋址,避免產生野指標;
- map中的key在不存在的時候,賦值陳述句其實會進行新的k-v值的插入,所以拒絕直接尋址結構體內的欄位,以防結構體不存在的時候可能造成的錯誤;
- 這可能和map的并發不安全性相關
解決方法:
-
整體更新map的value部分
type T struct { n int } func main(){ m := make(map[int]T) //m[0].n = 1 //map[key]struct 中 struct 是不可尋址的,所以無法直接賦值 t := m[0] t.n = 1 m[0] = t /*或 t := T{1} m[0] = t */ fmt.Println(m[0].n) } -
把map的value定義為指標型別
type T struct {
n int
}
func main(){
m := map[int]*T{
0: &T{},
}
m[0].n = 1
fmt.Println(m[0].n)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/252187.html
標籤:區塊鏈
