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

 

相关文章:

  • 2021-06-01
  • 2022-12-23
  • 2022-12-23
  • 2021-06-02
  • 2021-10-17
  • 2021-09-03
  • 2021-11-27
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-11-12
  • 2021-07-21
  • 2021-05-24
  • 2021-06-09
相关资源
相似解决方案