通过其字符串名称类型转换为特定的结构类型

Typecast to a specific struct type by its string name

我想通过使用 struct/interface.

的字符串名称值将特定变量类型转换为特定定义的 struct/interface

例如:

type Testing interface{}

和新变量

stringName := "Testing"
newTestingVariable.(stringName)

这可能是偶然的吗?也许使用反射?

干杯

这是不可能的。 Go 是一种静态类型语言,这意味着必须在编译时知道变量和表达式的类型。

type assertion中:

x.(T)

[...] If the type assertion holds, the value of the expression is the value stored in x and its type is T.

因此您使用类型断言来获取(或测试)您指定类型的值。

你什么时候会做:

stringName := "Testing"
newTestingVariable.(stringName)

类型断言结果的类型是什么?你没有告诉。您指定了包含类型名称的 string 值,但这只能在 运行时 决定。 (是的,在上面的示例中,编译器可以跟踪该值,因为它是作为常量值给出的,但在一般情况下,这在编译时是不可能的。)

所以在编译时编译器只能使用interface{}作为类型表达式结果的类型,那有什么意义呢?

如果重点是动态测试 x 的类型是否为 T(或者如果接口值 x 实现 T),您可以为此使用反射(包 reflect)。在这种情况下,您将使用 reflect.Type 来指定要测试的类型,而不是其名称的 string 表示。