如何在不使用反射的情况下优雅地在 golang 中动态调用方法?

How do I elegantly call a method dynamically in golang without using reflection?

我正在使用反射来执行此操作:

        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{})
    }

但必须有更好的方法。上面代码的重点是摆脱:

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

我不想有一个大的 if else 树。这是一个 ftp 服务器 http://github.com/andrewarrow/paradise_ftp,我需要处理 15 个左右的命令,例如 "USER" 和 "PASS" 和 "QUIT" 等等。我希望每一个调用类似 "handleUser" 或 "handlePass" 的方法。但是使用反射是一个坏主意。太慢了。

从您的链接用例来看,将字符串映射到函数似乎效果最好。示例:

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

调用函数:

name := "USER"
if fn := m[name]; fn != nil {
    fn(self) // where self is *Paradise
}