将动态参数传递给函数

I’ve a function which should do something like this


func getA(m *m.TSR, bl string) string {
    runParams, exist := m.BuildParams.Before[bl]
    if exist {
        runParamsMap, ok := runParams.(map[interface{}]interface{})
        if ok {
            run, ok := runParamsMap["builder"]
            if ok {
                return run.(string)
            }
        }
    }
    return ""
}


func getB(m *m.TSR, bl string) string {
    runParams, exist := m.BuildParams.After[bl]
    if exist {
        runParamsMap, ok := runParams.(map[interface{}]interface{})
        if ok {
            run, ok := runParamsMap["builder"]
            if ok {
                return run.(string)
            }
        }
    }
    return ""
}

Both function are working as expected , but I wonder if there is a way to use just only one function that handle the same ? The only difference is the Before & After

m.BuildParams.Before[bl]

m.BuildParams.After[bl]

All the reset is exactly the same, any idea how to combine them without removing the those line outside the function ….

maybe with additional parameter ....

One option is to move the common part to another function, e.g. get(), and change getA() and getB() to call this get():

func getB(m *m.TSR, bl string) string {
    runParams, exist := m.BuildParams.Before[bl]
    return get(runParams, exist)
}

func getB(m *m.TSR, bl string) string {
    runParams, exist := m.BuildParams.After[bl]
    return get(runParams, exist)
}

func get(runParams interface{}, exists bool) string {
    if exist {
        runParamsMap, ok := runParams.(map[interface{}]interface{})
        if ok {
            run, ok := runParamsMap["builder"]
            if ok {
                return run.(string)
            }
        }
    }
    return ""
}

If m.BuildParams.Before and m.BuildParams.After are of the same type (be it commonType), you can do better:

func getA(m *m.TSR, bl string) string {
    return get(m.BuildParams.Before, bl)
}

func getB(m *m.TSR, bl string) string {
    return get(m.BuildParams.After, bl)
}

And only the first line changes in get():

func get(common commonType, bl string) string {
    runParams, exist := common[bl]
    // rest is same
}