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