本文介绍了我可以对 trait 对象进行类型自省,然后向下转换吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Trait 的集合,一个迭代它并执行某些操作的函数,然后我想检查实现者类型,以及它是否属于 Foo 然后向下转换它并调用一些 Foo 方法.

I have a collection of Trait, a function that iterates over it and does something, and then I would like to check the implementor type and if it is of type Foo then downcast it and call some Foo method.

基本上,类似于 Go 的 type-switch接口转换.

Basically, something similar to Go's type-switch and interface conversion.

四处搜索我发现了 Any trait 但它只能在 'static 类型上实现.

Searching around I found about the Any trait but it can only be implemented on 'static types.

帮助展示我想要的:

let vec: Vec<Box<Trait>> = //

for e in vec.iter() {
    e.trait_method();

    // if typeof e == Foo {
    // let f = e as Foo;
    // f.foo_method();
    //}
}

推荐答案

正如你所注意到的,向下转换只适用于 Any trait,是的,它只支持 'static 数据.你可以在这里找到最近关于为什么会这样的讨论.基本上,为任意生命周期的引用实现反射很困难.

As you have noticed, downcasting only works with Any trait, and yes, it only supports 'static data. You can find a recent discussion on why it is so here. Basically, implementing reflection for references of arbitrary lifetimes is difficult.

也不可能(至少到目前为止)将 Any 与您的自定义特征轻松结合起来.但是,最近创建了一个宏库,用于自动实现您的特征的Any.你也可以在这里找到一些关于它的讨论.

It is also impossible (as of now, at least) to combine Any with your custom trait easily. However, a macro library for automatic implementation of Any for your trait has recently been created. You can also find some discussion on it here.

这篇关于我可以对 trait 对象进行类型自省,然后向下转换吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 20:57