Removing a key from the card using the reflection change key? This is mistake?

I am trying to remove the same key from two cards using reflection. However, deleting it from the first card causes a change in the key value. This is a WAI or error.

Code in ( http://play.golang.org/p/MIkFP_Zrxb ):

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

produces this conclusion:

map[a:true b:true]
KEY BEFORE a
m1: map[b:true]
KEY AFTER 
KEY AFTER SECOND CALL 
m2: map[a:true b:true]

Please note that the value of "a" is not removed from m2. Commenting out the specified line makes v2.SetMapIndex work.

Also note that the value of "k" changes after calling SetMapIndex. It seems that SetMapIndex is not working. Can anyone suggest an explanation? This is mistake? Any suggested solution?

Thank.

+4
source share
3 answers

: https://code.google.com/p/go/issues/detail?id=7896

, .

, , , , , . (I.e., SetMapIndex() , .

0

, ? reflect.SetMapIndex , " val - , SetMapIndex ". , , , - ? , k - string:

fmt.Println(k.Kind())
fmt.Println(k.Len())

:

string
0
0

SetMapIndex / .

. / , .

, , k2 := v2.MapKeys()[0] v2. , , . , , .

, :

http://golang.org/src/pkg/reflect/value.go

http://golang.org/src/pkg/runtime/hashmap.c

-1

Source: https://habr.com/ru/post/1538624/


All Articles