dougan5772 2014-09-27 15:23
浏览 36
已采纳

GO:查找/扫描结构/功能

Is it possible in GO to find structs or functions by criteria such as name, tag or interface? i.e something along the lines of command line tasks/verbs? i.e:

func cmd1() {
    ...
}

func cmd2() {
    ...
}

...

func cmdN() {
}

func main() {
    // Inspect os.Args and call cmd{X}() based on args.
    ...
}

I don't mind what the exact mechanism is and if the final targets are functions or structs - the goal is to get something working by convention without any boilerplate code.

  • 写回答

2条回答 默认 最新

  • dtncv04228 2014-09-27 15:48
    关注

    You could use reflection

    package main
    
    import (
        "flag"
        "fmt"
        "reflect"
    )
    
    var cmd command
    
    type command struct{}
    
    func (c command) execute(name string) {
        v := reflect.ValueOf(c)
    
        cmd := v.MethodByName(name)
        if !cmd.IsValid() {
            fmt.Println(name + " not a command")
            return
        }
    
        cmd.Call([]reflect.Value{})
    }
    
    func (c command) Cmd1() {
        fmt.Println("command 1")
    }
    
    func (c command) Cmd2() {
        fmt.Println("command 2")
    }
    
    func (c command) Cmd3() {
        fmt.Println("command 3")
    }
    
    func main() {
        flag.Parse()
    
        cmd.execute(flag.Arg(0))
    }
    

    or you could use a map.

    package main
    
    import (
        "flag"
        "fmt"
    )
    
    func cmd1() {
        fmt.Println("command 1")
    }
    
    func cmd2() {
        fmt.Println("command 2")
    }
    
    func cmd3() {
        fmt.Println("command 3")
    }
    
    var funcs = map[string]func(){
        "cmd1": cmd1,
        "cmd2": cmd2,
        "cmd3": cmd3,
    }
    
    func main() {
        flag.Parse()
    
        if f, ok := funcs[flag.Arg(0)]; ok {
            f()
        } else {
            fmt.Println(flag.Arg(0) + " command not found")
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?