Reputation: 1972
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
Upvotes: 3
Views: 1388
Reputation: 1972
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()))
Upvotes: 2
Reputation: 120989
Here's one way to create a reflect.Value
for a nil
value of type interface{}
:
rkey := reflect.ValueOf(new(interface{})).Elem()
Upvotes: 5