-
Notifications
You must be signed in to change notification settings - Fork 17.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
reflect: SetMapIndex does not permit adding nil values of interface type #34898
Comments
The docs says, if the second argument of a |
If you do want to add a nil element entry, you can do it like: func addAsHello(y interface{}) {
m := map[string]interface{}{}
// Add an entry for `hello` with the value nil value using reflection
mr := reflect.ValueOf(m)
var element reflect.Value
if y == nil {
element = reflect.ValueOf(&y).Elem()
} else {
element = reflect.ValueOf(y)
}
mr.SetMapIndex(reflect.ValueOf(`hello`), element)
fmt.Println(m)
// Do the same without reflection
m[`hello`] = y
fmt.Println(m)
fmt.Println()
} |
I've read the docs. I'm passing a Perhaps the documentation needs some clarification? |
The docs of I'm happy to entertain doc clarifications if you have suggestions. But any changes need to be consistent with how |
@thallgren |
Ok. I understand what I interpreted wrong in the docs. From the docs on
I immediately understood this. The zero value of the
Admittedly, there's a capital |
The reflect docs should use If we're going to fix any wording, we would want to fix it everywhere in the docs. Instead of and/or in addition to "x is the zero Value" we could say "!x.IsValid()" or something (see the doc for |
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?
The text was updated successfully, but these errors were encountered: