在包含地图[int] * somepointer的接口{}上循环

时间:2019-06-20 14:14:15

标签: go

我必须处理很多带有int键的映射,这些键包含指向不同数据类型的指针。

我需要一个函数(每种地图类型不需要10个函数)来遍历那些地图并获取最大和最小键值。

2 个答案:

答案 0 :(得分:3)

使用反射包对具有整数键和任意值类型的地图进行操作:

func getMaxKey(inout interface{}) int {
    keys := reflect.ValueOf(inout).MapKeys()
    if len(keys) == 0 {
        return 0
    }
    max := keys[0].Int()
    for _, key := range keys[1:] {
        n := key.Int()
        if n > max {
            max = n
        }
    }
    return int(max)
}

Run it on the playground

答案 1 :(得分:-1)

这是我想出的。它可能也适用于其他地图类型:

https://play.golang.org/p/-T8s-bPCNm4

  • 它允许传入map [int] * somepointer类型的任何地图
  • 不需要类型断言(在这种情况下)

-

func getMaxKey(inout interface{}) int {
    auxMap:= make(map[int]string)
    body, _ := json.Marshal(inout)
        json.Unmarshal(body, &auxMap)
    maxKey := 0
        for key,_ := range auxMap {
        if key > maxKey {
            maxKey = key
        }
    }
    return maxKey
}


func getMinKey(inout interface{}) int {
    auxMap:= make(map[int]string)
    body, _ := json.Marshal(inout)
        json.Unmarshal(body, &auxMap)
    minKey := 0
        for key,_ := range auxMap {
        if key < minKey || minKey == 0 {
            minKey = key
        }
    }
    return minKey
}