英文:
How to "delete" a key from a map in Go (golang) using reflection
问题
我正在尝试使用反射从映射中删除一个键,但是我找不到方法来实现。我有以下代码(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\n", m)
m = map[string]bool{
"a": true,
"b": true,
}
m["a"] = false
fmt.Printf("ASSIGN: %v\n", 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\n", m)
}
它生成以下输出:
DELETE: map[b:true]
ASSIGN: map[a:false b:true]
REFLECT: map[a:false b:true]
正如你所看到的,反射的情况似乎与赋值一个零值相同,而不是删除它。这似乎与 reflect.SetMapIndex() 的文档相矛盾,文档中说(http://golang.org/pkg/reflect/#Value.SetMapIndex):
如果 val 是零值,则 SetMapIndex 会从映射中删除键。
对于我的应用程序,我需要实际上从映射中删除该键。有什么想法吗?
英文:
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\n", m)
m = map[string]bool{
"a": true,
"b": true,
}
m["a"] = false
fmt.Printf("ASSIGN: %v\n", 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\n", 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
得分: 10
与其使用表示映射值类型的零值的reflect.Value
,SetMapIndex
函数期望使用表示reflect.Value
本身的零值来删除一个键。因此,你需要像这样进行操作:
v.SetMapIndex(reflect.ValueOf("a"), reflect.Value{})
英文:
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{})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论