dongta1824 2015-04-30 10:55
浏览 56
已采纳

golang进行反射。Type[duplicate]

This question already has an answer here:

My Problem is as follows:

I have a slice of reflect.Value, that was returned from a MethodByName("foo").Call().

now i want to cast the contained values to their types, which i dont know statically, but in form of relflect.Type

Basically what i want to do is:

values[0].Interface().(mytype)

but with reflection

values[0].Interface().(reflect.TypeOf(responseObject))

This gives me the compilation error:

reflect.TypeOf(responseObject) is not a type

Is there a way to do this in go?

Thanks and regards

BillDoor

</div>
  • 写回答

2条回答 默认 最新

  • drv13270 2015-05-04 07:51
    关注

    What is a cast (type assertion)? It has two effects:

    1. At compile time, the compile-time of the whole type assertion expression is the type casted to.
    2. At runtime, a check is made on the actual runtime type of the value, and if it is not the type casted to, it will generate a runtime error.

    Obviously, #1 doesn't make sense for a type that is not known at compile-time, because how can the compile-time type of something depend on something not known at compile time?

    You can still do manually do #2 for a type that is not known at compile time. Just get the runtime type of the value using reflect.TypeOf() and compare it against the runtime.Type you have.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作