关于go中map的使用问题

gogoboy · 2018-04-11 08:51:35 · 1313 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2018-04-11 08:51:35 的主题,其中的信息可能已经有所发展或是发生改变。

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

... 这样写不是更科学么.但是编译器提示我不支持&.请问我该怎么作呢?


有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1313 次点击  
加入收藏 微博
4 回复  |  直到 2018-05-14 19:47:53
abin
abin · #1 · 7年之前

value 使用指针,使用值的话拿到的都是值的拷贝

gogoboy
gogoboy · #2 · 7年之前
abinabin #1 回复

value 使用指针,使用值的话拿到的都是值的拷贝

指针是可以但是总是感觉不够优雅。

zhaozonglu
zhaozonglu · #3 · 7年之前

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"}
13728605342
13728605342 · #4 · 7年之前
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传