cannot assign to struct field xxx in map


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

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 map

原因是 map 元素是无法取址的,也就说可以得到 a["tao"], 但是无法对其进行修改。

解决办法:使用指针的map

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)
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM