douwei1128
2015-03-23 09:53
浏览 291
已采纳

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

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

Basically I want to do this:

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

图片转代码服务由CSDN问答提供 功能建议

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

基本上我想这样做: \ n

  theType:=反射.TypeOf(anInterfaceValue)
theConvertedValue:= anInterfaceValue。(theType)
   
 
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dshdb64088 2015-03-23 10:01
    已采纳

    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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题