dsmnedc798226 2014-04-29 18:06
浏览 14
已采纳

使用反射更改键从地图中删除键? 这是错误吗?

I am trying to remove the same key from two maps using reflection. However, removing it from the first map is causing a change to the key value. Is this WAI or a bug.

Code at (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 output:

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

Notice that the "a" value is not removed from m2. Commenting out the indicated line causes the call to v2.SetMapIndex to work.

Also notice that the value of "k" changes after the call to SetMapIndex. That appears to be the reason that SetMapIndex isn't working. Can anyone offer an explanation? Is this a bug? Any suggested workaround?

Thanks.

  • 写回答

3条回答 默认 最新

  • duanbi8089 2014-04-30 04:46
    关注

    I filed a bug: https://code.google.com/p/go/issues/detail?id=7896

    It's fixed in the tip, but hasn't propagated out to the stable release.

    The workaround for this is to structure the code so that the map which is the source of the key is the last map from which it's deleted. (I.e., reversing the calls to SetMapIndex() in the original post will behave as expected.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题