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

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

报告相同问题?

悬赏问题

  • ¥15 蓝桥oj3931,请问我错在哪里
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染