如何在Golang中的运行时中动态转换类型?

Lei*_*Cao 0 reflection runtime go

这是我的示例:http : //play.golang.org/p/D608cYqtO5

基本上我想这样做:

theType := reflect.TypeOf(anInterfaceValue)
theConvertedValue := anInterfaceValue.(theType)
Run Code Online (Sandbox Code Playgroud)

thw*_*hwd 5

记号

value.(type)
Run Code Online (Sandbox Code Playgroud)

被称为类型断言type断言中的in必须在编译时知道,并且它始终是类型名称。

在您的游乐场示例中,SetStruct2可以使用类型开关为其第二个参数处理不同的类型:

switch v := value.(type) {
case Config:
    // code that uses v as a Config
case int:
    // code that uses v as an int
}
Run Code Online (Sandbox Code Playgroud)

但是,您不能断言接口是动态的(例如在代码中)。因为否则编译器将无法对您的程序进行类型检查。

编辑:

如果没有其他方法,我不想一一列举吗?

您可以使用反射来进行类型无关的工作。然后,您可以在值上随机设置填充,但是如果您对类型执行非法操作,它将引起恐慌。

如果要从编译器的类型检查中受益,则必须枚举不同的情况。