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

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

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

Basically I want to do this:

theType := reflect.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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了