dongta1824 2015-04-30 02: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-03 23: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部