How can I convert type dynamically in runtime in Golang?

huangapple go评论106阅读模式
英文:

How can I convert type dynamically in runtime in Golang?

问题

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

基本上我想要做这个:

theType := reflect.TypeOf(anInterfaceValue)
theConvertedValue := anInterfaceValue.(theType)
英文:

Here is my example:
http://play.golang.org/p/D608cYqtO5

Basically I want to do this:

theType := reflect.TypeOf(anInterfaceValue)
theConvertedValue := anInterfaceValue.(theType)

答案1

得分: 5

这里的注释value.(type)被称为type-assertion。断言中的type必须在编译时已知,并且它始终是一个类型名称。

在你的示例中,SetStruct2可以使用type-switch来处理第二个参数的不同类型:

switch v := value.(type) {
case Config:
    // 使用v作为Config的代码
case int:
    // 使用v作为int的代码
}

然而,你不能将接口断言为动态类型(就像你的代码中那样)。否则,编译器将无法对你的程序进行类型检查。

编辑:

> 如果有其他方法,我不想一个一个地进行类型判断怎么办?

你可以使用反射来以类型无关的方式处理。然后,你可以随机地在值上设置东西,但如果对于某个类型执行非法操作,它将引发恐慌。

如果你想从编译器的类型检查中受益,你将不得不枚举不同的情况。

英文:

The notation

value.(type)

is called a type-assertion. The type in an assertion has to be known at compile-time and it's always a type name.

In your playground example SetStruct2 could use a type-switch to handle different types for its second argument:

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

You cannot, however, assert an interface to be something dynamic (like in your code). Because otherwise the compiler could not type-check your program.

Edit:

> I don't want to case them one by one if there is another way to do so?

You can use reflection to work type-agnostically. You can then set stuff randomly on values but it will panic if you perform an illegal operation for a type.

If you want to benefit from the compiler's type checks you'll have to enumerate the different cases.

huangapple
  • 本文由 发表于 2015年3月23日 17:53:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/29207232.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定