shirobert 发表于 2018-9-21 09:28:24

cannot assign to struct field xxx in map

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

type sstruct{  name string
  age int
  }
  func main(){
  a := maps{
  "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 sstruct{  name
string  age
int  
}
  
func main(){
  a :
= map*s{"tao":{"li",18,},  }
  

  fmt.Println(a[
"tao"].age)  a[
"tao"].age += 1  fmt.Println(a[
"tao"].age)  
}
  



页: [1]
查看完整版本: cannot assign to struct field xxx in map