briancrypto
briancrypto

Reputation: 31

golang when iterate map, how to get key as pointer?

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.

package main

import "fmt"

type MyIntC struct {
   MyInt int
}

func main() {
  slice := make([]*MyIntC,0, 5)
  myInt5 := &MyIntC{MyInt: 50}
  myInt6 := &MyIntC{MyInt: 60}
  myInt7 := &MyIntC{MyInt: 70}

  mapInts := make(map[MyIntC]string)
  mapInts[*myInt5] = "something 50"
  mapInts[*myInt6] = "something 60"
  mapInts[*myInt7] = "something 70"
  for k, _ := range mapInts {
     slice = append(slice, &k)
  }

  for _, item := range slice {
     fmt.Println(item)
  }  
}

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.

Upvotes: 2

Views: 2395

Answers (1)

abhink
abhink

Reputation: 9136

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

Upvotes: 3

Related Questions