How do I access a map keyword using reflection?

I have a null key card:

mapp := map[interface{}]interface{}{
    nil: "a",
}

      

Accessing it nil key directly works:

fmt.Println("key[nil]:", mapp[nil])

      

But with reflection this is not the case - how to do it?

rmapp := reflect.ValueOf(mapp)
rkey := reflect.ValueOf(interface{}(nil))
rval := rmapp.MapIndex(rmapp.MapIndex(rkey))
fmt.Println("key[nil]:", rval)

      

The broken code is here:
https://play.golang.org/p/6TKN_tDNgV

+3


source to share


2 answers


The missing element appears to have been a null value of the map key type, which is required to access the nil key on the map.

refmap.MapIndex(reflect.Zero(refmap.Type().Key()))

      



playground example

+2


source


Here's one way to create a value reflect.Value

for a nil

type interface{}

:

rkey := reflect.ValueOf(new(interface{})).Elem()

      



playground example

+5


source







All Articles