dragon071111 2018-12-02 11:07
浏览 793

在GoLang中将字符串转换为func类型

I have a string which is the name of a function in GoLang. I want to treat them as function. How should I do this? I tried to achieve it through reflect.* but I didn't find a valid path for my purpose.

I get the name fo handlers in a JSON file, and I want to execute those handlers. Something like this:

{
  "students/show" : "ShowStudents",
  "students/add" : "AddStudents"
}

Then I want to execute ShowStudents(), but don't know how to treat it like a variable of type func

  • 写回答

2条回答 默认 最新

  • douxu5845 2018-12-02 12:00
    关注

    establish a mapping between the keys in the json file and the functions, then use that to call the functions as they appear in the json

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    func AddStudents() {
        fmt.Println("woo")
    }
    
    func ShowStudents() {
        fmt.Println("lots of students")
    }
    
    func main() {
        js := `{
      "students/show" : "ShowStudents",
      "students/add" : "AddStudents"
    }`
    
        lookup := make(map[string]string)
        json.Unmarshal([]byte(js), &lookup)
        dispatch := make(map[string]func())
        dispatch["students/show"] = ShowStudents
        dispatch["students/add"] = AddStudents
    
        for v, _ := range lookup {
            print(v)
            dispatch[v]()
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?