【发布时间】:2021-08-26 06:24:55
【问题描述】:
这个问题已经用许多其他语言回答。在带有简单地图(无嵌套)的 golang 中,如何找出一个地图是否是另一个地图的子集。例如:map[string]string{"a": "b", "e": "f"} 是map[string]string{"a": "b", "c": "d", "e": "f"} 的子集。我想要一个通用的方法。我的代码:
package main
import (
"fmt"
"reflect"
)
func main() {
a := map[string]string{"a": "b", "c": "d", "e": "f"}
b := map[string]string{"a": "b", "e": "f"}
c := IsMapSubset(a, b)
fmt.Println(c)
}
func IsMapSubset(mapSet interface{}, mapSubset interface{}) bool {
mapSetValue := reflect.ValueOf(mapSet)
mapSubsetValue := reflect.ValueOf(mapSubset)
if mapSetValue.Kind() != reflect.Map || mapSubsetValue.Kind() != reflect.Map {
return false
}
if reflect.TypeOf(mapSetValue) != reflect.TypeOf(mapSubsetValue) {
return false
}
if len(mapSubsetValue.MapKeys()) == 0 {
return true
}
iterMapSubset := mapSubsetValue.MapRange()
for iterMapSubset.Next() {
k := iterMapSubset.Key()
v := iterMapSubset.Value()
if value := mapSetValue.MapIndex(k); value == nil || v != value { // invalid: value == nil
return false
}
}
return true
}
当我想检查集合映射中是否存在子集映射键时,MapIndex 返回类型的零值,并且无法将其与任何内容进行比较。
毕竟我能把同样的工作做得更好吗?
【问题讨论】:
标签: dictionary go generics reflection go-map