duanhong1985 2018-10-25 21:16
浏览 58
已采纳

为什么地图上没有按键

I created a map:

l := make(map[*A]string)

where A is:

type A struct{}

Then added key-values into it:

a1 := &A{}
a2 := &A{}
a3 := &A{}

l[a1] = "a1"
l[a2] = "a2"
l[a3] = "a3"

I expected to see all values ("a1", "a2", "a3") while doing range

for k, v := range l{
    fmt.Println(k, v)
}

But I see only the last one.

Why that happens? https://play.golang.org/p/GSdUWzExxLK

  • 写回答

2条回答 默认 最新

  • dtng25909 2018-10-25 21:22
    关注

    Because your struct has no fields, Go optimizes away all pointers to it to the same address, so you're using the same key every time. Give the struct a field (even if you never put a value in it) and you'll get your expected behavior.

    Playground: https://play.golang.org/p/n-WUZ9wqpGJ

    You can read more about empty structs (including this pointer behavior) on Dave Cheney's blog.

    It's mentioned only briefly in the spec, under Sizes and Alignments, and is in fact the very last sentence in the spec:

    A struct or array type has size zero if it contains no fields (or elements, respectively) that have a size greater than zero. Two distinct zero-size variables may have the same address in memory.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?