这个问题已经以许多其他语言得到回答。在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
毕竟,我能把同样的工作做得更好吗?
LEATH
人到中年有点甜
蓝山帝景
相关分类