简体   繁体   English

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

[英]Casting a string to a func type in GoLang

I have a string which is the name of a function in GoLang. 我有一个字符串,它是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. 我在JSON文件中获得处理程序的名称,我想执行这些处理程序。 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 然后我想执行ShowStudents() ,但是不知道如何将其视为func类型的变量

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 在json文件中的键和函数之间建立映射,然后使用它们来调用出现在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]()
    }
}

Your task can be broken down into two steps: 您的任务可以分为两个步骤:

  1. Extract function names 提取函数名称
  2. Run those functions (assuming that they are defined somewhere) 运行这些函数(假设它们在某处定义)

For step 1, I would unmarshal the JSON into a map[string]string, something like this: 对于步骤1,我将将JSON解组为map [string] string,如下所示:

b, err := ioutil.ReadFile(fname)
mp := make(map[string]string)
json.Unmarshal(b, &mp)

Coming to Step 2. In Go, it's not possible to convert string directly to a function call, but it is possible to enumerate the methods of an object using reflect package. 转到步骤2。在Go中,不可能将string直接转换为函数调用,但是可以使用reflect包枚举对象的方法。 This can be used as a workaround in this case. 在这种情况下,可以将其用作解决方法。 Instead of writing those functions directly, bind them to a dummy type, something like this: 与其直接编写这些函数,不如将它们绑定到一个虚拟类型,如下所示:

type T int

func (t T) ShowStudents() {
    fmt.Println("Showing Students")
}

func (t T) AddStudents() {
    fmt.Println("Adding Students")
}

func main() {
    var t T
    reflect.ValueOf(t).MethodByName("ShowStudents").Call(nil)
}

Run this example 运行这个例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM