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

I have to deal with a lot of maps with int keys which contain pointers to different datatypes.

I need a function (and not 10 functions for each map type) to range over those maps and get the maximum and minimum key values.

Use the reflect package to operate on maps with integer keys and arbitrary value types:

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.

This is what I came up with. It might also work for other map types:

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

  • It allows to have passed in any map of type map[int]*somepointer
  • No type assertion needed (in this case)

-

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
}