cannot assign to struct field xxx in map

golang 中对 map 类型中的 struct 赋值报错golang

type s  struct{
name string
age int
}
func main(){
a := map[string]s{
"tao":{
"li",
18,},
}

fmt.Println(a["tao"].age)
a["tao"].age += 1 //注释后能够执行
fmt.Println(a["tao"].age)
}

./test.go:16:15: cannot assign to struct field a["tao"].age in mapspa

缘由是 map 元素是没法取址的,也就说能够获得 a["tao"], 可是没法对其进行修改。指针

解决办法:使用指针的mapcode

type s  struct{
    name string
    age int
}
func main(){
    a := map[string]*s{ "tao":{
            "li",
            18,},
    }

    fmt.Println(a["tao"].age)
    a["tao"].age += 1
    fmt.Println(a["tao"].age)
}
相关文章
相关标签/搜索