关于go中map的使用问题

gogoboy · · 1077 次点击
value 使用指针,使用值的话拿到的都是值的拷贝
#1
更多评论
指针是可以但是总是感觉不够优雅。
#2
value使用指针,如果直接用`point.value1=a`这样赋值的话,会panic吧,空指针呀 ``` type Student struct { Name1 string Name2 string Name3 string Name4 string } func main() { stus := map[string]*Student{} stus["stu001"].Name1 = "a" //这里会报 panic: runtime error: invalid memory address or nil pointer dereference stus["stu001"].Name2 = "b" stus["stu001"].Name3 = "c" stus["stu001"].Name4 = "d" fmt.Println(stus) } ``` 如果value不用指针 `stus := map[string]Student{}` 不能使用 `stus["stu001"].Name1 = "a" `直接赋值,编辑就会报错 `cannot assign to struct field stus["stu001"].Name1 in map` 而 `stus := &map[string]Student{}` 更是不对,因为这个时候 stus是一个指针类型 `*map[string]Student` 不支持indexing,编译会报`type *map[string]Student does not support indexing` 正确为使用为 ``` stus := map[string]Student{} stus["stu001"] = Student{Name1: "a", Name2: "b"} ``` 或者 ``` stus := map[string]*Student{} stus["stu001"] = &Student{Name1: "a", Name2: "b"} ```
#3