按元素类型过滤向量

问题描述 投票:0回答:1

有没有办法实现下面的功能?

trait X {}

struct A;
struct B;

impl X for A {}
impl X for B {}

/// Only keep elements of type A
fn filter(list: Vec<Box<dyn X>>) -> Vec<Box<A>> {
    todo!();
}

在 dart 中,这可能要容易得多:

List<A> filter(list: List<X>) {
     return list.whereType<A>();
}
rust filter traits
1个回答
0
投票

你需要使用某种向下转型的方式。正如如何从特征对象获取对具体类型的引用?中所解释的,稳定的方法是添加一个

as_any()
方法:

use std::any::Any;

trait X {
    fn as_any_box(self: Box<Self>) -> Box<dyn Any>;
}

struct A;
struct B;

impl X for A {
    fn as_any_box(self: Box<Self>) -> Box<dyn Any> {
        self
    }
}
impl X for B {
    fn as_any_box(self: Box<Self>) -> Box<dyn Any> {
        self
    }
}

/// Only keep elements of type A
fn filter(list: Vec<Box<dyn X>>) -> Vec<Box<A>> {
    list.into_iter()
        .filter_map(|v| v.as_any_box().downcast::<A>().ok())
        .collect()
}
© www.soinside.com 2019 - 2024. All rights reserved.