2

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 Answers1

3

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

abhink
  • 8,740
  • 1
  • 36
  • 48