douyin8809 2019-03-06 14:53
浏览 11
已采纳

将动态参数传递给函数

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 ....

  • 写回答

1条回答 默认 最新

  • duandeng1824 2019-03-06 15:00
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题