Skip to content

reflect: Calling reflect.SetMapIndex(k, v) causes mutations to k if k is removed in the map #7896

Closed
@gopherbot

Description

@gopherbot

by gmadrid:

See code at http://play.golang.org/p/MIkFP_Zrxb

What does 'go version' print?
go version go1.2.1 darwin/amd64

What steps reproduce the problem?
Calling reflect.SetMapIndex() causes changes to the key that prevent future calls to
SetMapIndex from working.

If possible, include a link to a program on play.golang.org.
http://play.golang.org/p/MIkFP_Zrxb

What happened?
1. Run the linked code.
2. Notice that the key after the call to SetMapIndex is different
3. Notice that the second call to SetMapIndex doesn't work.

What should have happened instead?
The key should be unchanged and both calls to SetMapIndex should work.


Code copied below: 

package main

import (
    "fmt"
    "reflect"
)

func main() {
    m1 := map[string]bool{"a": true, "b": true}
    m2 := map[string]bool{"a": true, "b": true}

    fmt.Println(m1)

    v1 := reflect.ValueOf(m1)
    k := v1.MapKeys()[0]

    fmt.Println("KEY BEFORE", k)
    v1.SetMapIndex(k, reflect.Value{})  // COMMENT THIS OUT
    fmt.Println("m1:", m1)
    fmt.Println("KEY AFTER", k)

    v2 := reflect.ValueOf(m2)
    v2.SetMapIndex(k, reflect.Value{})
    fmt.Println("KEY AFTER SECOND CALL", k)
    fmt.Println("m2:", m2)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions