Gima
Gima

Reputation: 1972

How to access map's nil key using reflection?

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

Answers (2)

Gima
Gima

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()))

playground example

Upvotes: 2

Thundercat
Thundercat

Reputation: 120989

Here's one way to create a reflect.Value for a nil value of type interface{}:

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

playground example

Upvotes: 5

Related Questions