在对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的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)
}
map[key]struct 中 struct 是不可寻址的,所以无法直接赋值
原文:https://www.cnblogs.com/zmk-c/p/14496658.html