1. 首页
  2. 主题
  3. Go问与答

关于go中map的使用问题

gogoboy · · 1707 次点击
map[key] 可以获取到value的引用,但是这个引用如何记录呢? 比如我的value有100个成员变量 map[key].value1 = a map[key].value2 = b map[key].value3 = c ... 这样写下去不是要有100次检索的过程么.这不科学啊. point := &map[key] point .value1 = a point .value2 = b point .value3 = c ... 这样写不是更科学么.但是编译器提示我不支持&.请问我该怎么作呢?
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

用户登录

没有账号?注册

今日阅读排行

    加载中

一周阅读排行

    加载中