struct结构体不能赋值变通方案

2020-02-09  本文已影响0人  渣渣曦

在处理map中结构体元索变更时会出错,代码与错误如下:

package main

import "fmt"

type Animal struct {
    count int
}

func main() {
    m := map[string]Animal{"cat": Animal{2}, "dog": Animal{3}, "mouse": Animal{5}}
        fmt.Println(m)
    m["dog"].count = 4
    
    fmt.Println(m)

}

错误如下:

main.go:12: cannot assign to struct field m["dog"].count in map

指针存储会解决上述问题,代码如下:

package main

import "fmt"

type Animal struct {
    count int
}

func main() {
    m := map[string]*Animal{"cat": &Animal{2}, "dog": &Animal{3}, "mouse": &Animal{5}}
    fmt.Printf("%#v\n",m["dog"])
    m["dog"].count = 4
    fmt.Printf("%#v", m["dog"])
}
上一篇下一篇

猜你喜欢

热点阅读