假设我有这个结构和一个方法:
package main
import (
"fmt"
"reflect"
)
type MyStruct struct {
}
func (a *MyStruct) AAction() {
fmt.Println("Hello a")
}
现在,如果我想通过字符串调用方法“AAction”,我可以使用反射(这可行):
func main() {
reflect.New(reflect.TypeOf(MyStruct{})).MethodByName("AAction").Call([]reflect.Value{})
}
问题是,我不想将 MyStruct{} 用作表达式,而是用作字符串。当然这是行不通的:
func main() {
theStruct := "MyStruct"
theAction := "AAction"
reflect.New(reflect.TypeOf(theStruct)).MethodByName(theAction).Call([]reflect.Value{})
}
因为 reflect.Typeof(theStruct) 将是一个字符串。 我试着通读文档,遗憾的是,我找不到任何有用的东西。
我发现了这个类似的问题:Call a Struct and its Method by name in Go?
在已接受的问题下,OP 会问:
The issue in my case Is I cant not declare t is typed T, its must be some how I can declare t typed T by the name of T is string "T"
由
回答[...] I would suggest to match the name against the string "T" somewhere in your code [...]
这并没有解决问题,因为我仍然需要在某处调用 MyStruct{}
。
问题是:有没有办法通过将名称作为字符串来使用结构? (无需手动将结构的名称映射到结构)
使用 reflect.TypeOf(MyStruct{})
的工作版本:
PlayGround
无效版本,显然是在字符串上调用方法:PlayGround
最佳答案
对不起,你不能。答案是:您可以不。没有内置或预初始化的类型名称注册表。
要开始使用反射(reflect
包),您需要一个值(所讨论的类型)。基于string
(类型的string
名称),获取不到该类型的值,所以无法启动。
如果您只想通过 string
类型名称来执行您想要的操作,则需要在执行您想要的操作之前构建您自己的“注册表”。
关于反射:按字符串构造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36424907/