douyin2883 2017-09-23 07:44 采纳率: 0%
浏览 29
已采纳

golang迭代地图时,如何获取键作为指针?

Currently I am storing a map with key being a Struct (MyIntC). I would like to retrieve all the key in the map as a slice. The slice will be pointer to map key. This is so there is no copy of multiple key.

When I tried in here (https://play.golang.org/p/bclmCh_YV5), it is not working.

All elements in the slice will point to the last map key element iterated.

Why is that so? How could I overcome this?

Note: I suspect it is very similar issue to Slice of structs vs a slice of pointers to structs, in which I am always using the local variable address.

Thanks.

  • 写回答

1条回答 默认 最新

  • dongzine3782 2017-09-23 07:55
    关注

    You are correct about the issue being related to k in the range loop. k is a local variable and in each iteration you are simply adding the same pointer address to slice.

    You can always use pointer to a MyIntC as map key.

    // ...
    slice := make([]*MyIntC,0, 5)
    // ...
    mapInts := make(map[*MyIntC]string)
    // ...
    for k, _ := range mapInts {
       slice = append(slice, k)
    }
    // ...
    

    Working example: https://play.golang.org/p/Opd7RVywNa

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效