donglian1384 2014-04-29 07:23
浏览 89
已采纳

如何使用反射从Go(golang)的地图中“删除”键

I am trying to delete a key from a map using reflection, and I cannot find a way to do it. What am I missing? I have the below code (http://play.golang.org/p/7Et8mgmSKO):

package main

import (
    "fmt"
    "reflect"
)

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

    delete(m, "a")
    fmt.Printf("DELETE: %v
", m)

    m = map[string]bool{
        "a": true,
        "b": true,
    }

    m["a"] = false
    fmt.Printf("ASSIGN: %v
", m)

    m = map[string]bool{
        "a": true,
        "b": true,
    }
    v := reflect.ValueOf(m)
    v.SetMapIndex(reflect.ValueOf("a"), reflect.Zero(reflect.TypeOf(m).Elem()))
    fmt.Printf("REFLECT: %v
", m)
}

Which generates the output:

DELETE: map[b:true]
ASSIGN: map[a:false b:true]
REFLECT: map[a:false b:true]

As you can see, the reflection case seems to be identical to assigning a zero value, not deleting it. This seems to be contrary to the documentation for reflect.SetMapIndex() which says (http://golang.org/pkg/reflect/#Value.SetMapIndex):

If val is the zero Value, SetMapIndex deletes the key from the map.

For my application, I need to actually remove the key from the map. Any ideas?

展开全部

  • 写回答

1条回答 默认 最新

  • dtbi27903 2014-04-29 07:31
    关注

    Rather than a reflect.Value that represents the zero value for the map's value type, SetMapIndex expects a zero value for reflect.Value itself in order to delete a key. So you instead want something like this:

    v.SetMapIndex(reflect.ValueOf("a"), reflect.Value{})
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部