I have a map that has a nil-keyed value:
mapp := map[interface{}]interface{}{
nil: "a",
}
Accessing it's nil key's directly works:
fmt.Println("key[nil]:", mapp[nil])
But using reflection it doesn't - how to do this?
rmapp := reflect.ValueOf(mapp)
rkey := reflect.ValueOf(interface{}(nil))
rval := rmapp.MapIndex(rmapp.MapIndex(rkey))
fmt.Println("key[nil]:", rval)
Non-working code here:
https://play.golang.org/p/6TKN_tDNgV
The missing piece appears to have been the zero value of the map's key type, which is needed to access the nil key of the map.
refmap.MapIndex(reflect.Zero(refmap.Type().Key()))
Here's one way to create a reflect.Value
for a nil
value of type interface{}
:
rkey := reflect.ValueOf(new(interface{})).Elem()