通过其字符串名称将类型转换为特定的结构类型 [英] Typecast to a specific struct type by its string name
问题描述
我想通过使用struct/interface的字符串名称值将特定变量转换为特定的已定义struct/interface.
I would like to typecast a specific variable to a specific defined struct/interface by using the string name value of the struct/interface.
例如:
type Testing interface{}
和新变量
stringName := "Testing"
newTestingVariable.(stringName)
这是偶然的吗?也许使用反射?
Is this possible by chance? Perhaps using reflection?
欢呼
推荐答案
这是不可能的. Go是一种静态类型的语言,这意味着必须在编译时知道变量和表达式的类型.
It is not possible. Go is a statically typed language, which means types of variables and expressions must be known at compile-time.
在类型声明中:
x.(T)
[...]如果类型断言成立,则表达式的值为存储在x
中的值,其类型为T
.
[...] If the type assertion holds, the value of the expression is the value stored in x
and its type is T
.
因此,您可以使用类型断言来获取(或测试)您指定的类型的值.
So you use type assertion to get (or test for) a value of a type you specify.
您何时会这样做:
stringName := "Testing"
newTestingVariable.(stringName)
类型断言的结果的类型是什么?你没说您指定了一个包含类型名称的string
值,但这只能在 runtime 中确定. (是的,在上面的示例中,编译器可以跟踪作为常量值给出的值,但是在一般情况下,在编译时是不可能的.)
What would be the type of the result of the type assertion? You didn't tell. You specified a string
value containing the type name, but this can only be decided at runtime. (Yes, in the above example the compiler could track the value as it is given as a constant value, but in the general case this is not possible at compile time.)
因此,在编译时,编译器只能将interface{}
用作类型表达式结果的类型,那又有什么用呢?
So at compile time the compiler could only use interface{}
as the type of the result of the type expression, but then what's the point?
如果要动态测试x
的类型是否为T
(或者如果接口值x
实现了T
),则可以对此进行反射(包 reflect
).在这种情况下,您可以使用reflect.Type
来指定要测试的类型,而不是其名称的string
表示形式.
If the point would be to dynamically test if x
's type is T
(or that if the interface value x
implements T
), you can use reflection for that (package reflect
). In this case you would use a reflect.Type
to specify the type to be tested, instead of a string
representation of its name.
这篇关于通过其字符串名称将类型转换为特定的结构类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!