What version of Go are you using (go version)?
I'm executing this on the Go playground (currently at 1.13.1). Sample provided.
What did you do?
I tried to add an entry to a map of type map[string]interface{} using reflection. The behavior differs depending on if the actual value is an interface or a concrete value. There seem to be no way to actually add a nil value based on an interface type alone. Example can be executed here: https://play.golang.org/p/yfQo-wyP0B9
package main
import (
"fmt"
"reflect"
"regexp"
)
func addAsHello(y interface{}) {
m := map[string]interface{}{}
// Add an entry for `hello` with the value nil value using reflection
mr := reflect.ValueOf(m)
mr.SetMapIndex(reflect.ValueOf(`hello`), reflect.ValueOf(y))
fmt.Println(m)
// Do the same without reflection
m[`hello`] = y
fmt.Println(m)
fmt.Println()
}
func main() {
addAsHello(nil)
addAsHello(fmt.Stringer(nil))
addAsHello((*regexp.Regexp)(nil))
}
What did you expect to see?
map[hello:<nil>]
map[hello:<nil>]
map[hello:<nil>]
map[hello:<nil>]
map[hello:<nil>]
map[hello:<nil>]
What did you see instead?
map[]
map[hello:<nil>]
map[]
map[hello:<nil>]
map[hello:<nil>]
map[hello:<nil>]
What version of Go are you using (
go version)?I'm executing this on the Go playground (currently at 1.13.1). Sample provided.
What did you do?
I tried to add an entry to a map of type map[string]interface{} using reflection. The behavior differs depending on if the actual value is an interface or a concrete value. There seem to be no way to actually add a nil value based on an interface type alone. Example can be executed here: https://play.golang.org/p/yfQo-wyP0B9
What did you expect to see?
What did you see instead?