Skip to content

reflect: SetMapIndex does not permit adding nil values of interface type #34898

Description

@thallgren

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>]

Metadata

Metadata

Assignees

No one assigned

    Labels

    DocumentationIssues describing a change to documentation.NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.compiler/runtimeIssues related to the Go compiler and/or runtime.

    Type

    No type

    Projects

    Status
    Triage Backlog

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions