douqiaolong0528 2016-03-13 21:35
浏览 109
已采纳

如何在golang中动态地调用方法而不使用反射?

I'm using reflection to do this:

        method_name := CommandMap[command]
    thing := reflect.ValueOf(self).MethodByName(method_name)
    thing_s := fmt.Sprintf("%s", thing)
    if thing_s == "<invalid reflect.Value>" {
        self.writeMessage(550, "not allowed")
    } else {
        thing.Call([]reflect.Value{})
    }

but there must be a better way. The point of the above code was to get rid of:

if command == "this" {
  runThis()
} else if command == "that" {
  runThat()
} etc. etc.

I want to not have a big if else tree. This is an ftp server http://github.com/andrewarrow/paradise_ftp and I need to handle 15 or so commands like "USER" and "PASS" and "QUIT" etc. etc. I want each one to call a method like "handleUser" or "handlePass". But using reflection is a bad idea. It's too slow.

  • 写回答

1条回答 默认 最新

  • dongliu6848 2016-03-13 21:50
    关注

    From your linked use case, it appears that having a map of strings to functions will work best. Example:

    func MakeCommandMap() map[string]func(*Paradise) {
        m := map[string]func(*Paradise){
            "USER": (*Paradise).HandleUser,
            "PASS": (*Paradise).HandlePass,
        }
        // ...
        return m
    }
    

    Calling the functions:

    name := "USER"
    if fn := m[name]; fn != nil {
        fn(self) // where self is *Paradise
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c