generics - 泛型函数可以用特征参数化吗?

标签 generics rust traits

是否可以将特征作为参数传递给像这样的通用函数?

trait Fnord {
    fn do_it(&self) -> i32 { 42 }
}

impl Fnord for i32 {}

fn iter_as<'a, T>(objs: &'a [i32]) -> impl Iterator<Item = & 'a dyn T>
{
    objs.iter().map(|o| o as &dyn T)
}

fn main() {
    let objs: Vec<i32> = vec![1, 2, 3];

    // Calls would look like this
    for s in iter_as::<Fnord>(&objs) {
        println!("{}", s.do_it());
    }
}

这给我带来了这些错误:

error[E0404]: expected trait, found type parameter `T`
 --> src/lib.rs:7:69
  |
7 | fn iter_as<'a, T>(objs: &'a [i32]) -> impl Iterator<Item = & 'a dyn T>
  |                                                                     ^ not a trait

error[E0404]: expected trait, found type parameter `T`
 --> src/lib.rs:9:35
  |
9 |     objs.iter().map(|o| o as &dyn T)
  |                                   ^ not a trait

warning: trait objects without an explicit `dyn` are deprecated
  --> src/lib.rs:16:24
   |
16 |     for s in iter_as::<Fnord>(&objs) {
   |                        ^^^^^ help: use `dyn`: `dyn Fnord`
   |
   = note: `#[warn(bare_trait_objects)]` on by default

也就是说,iter_as 是否可以接受一个特征作为通用参数,以便它可以返回该特征的可迭代对象?我已经搜索了很多答案,但此时我觉得我可能问错了问题。

背景是这样的。我有一个包含多个不同具体类型的向量的结构,所有这些向量都实现相同的特征。我希望结构体的 impl 有一个函数,可以返回所有存储对象的可迭代对象作为它们的任何共同特征。上面的 iter_as 是该(名义)函数的简化版本。也许我只是以一种尴尬的方式来处理 rust(即,也许我的想法太像 C++ 程序员了),所以另一种惯用的方法也很棒。

最佳答案

T 必须是具体类型而不是特征。我认为最接近您正在寻找的内容如下:

trait Fnord {
    fn do_it(&self) -> i32;
}

impl Fnord for i32 {
    fn do_it(&self) -> i32 {
        *self
    }
}

impl<'a> From<&'a i32> for &'a dyn Fnord {
    fn from(i: &'a i32) -> Self {
        i as _
    }
}

fn iter_as<'a, T, TObj>(objs: &'a [T]) -> impl Iterator<Item = TObj> + 'a
where
    TObj: 'a,
    TObj: From<&'a T>,
{
    objs.iter().map(|o| o.into())
}

fn main() {
    let objs: Vec<i32> = vec![1, 2, 3];

    for s in iter_as::<i32, &dyn Fnord>(&objs) {
        println!("{}", s.do_it()); // 1 2 3
    }
}

我不确定您是否选择了惯用的 Rust 方式来执行此操作:因为您知道对象中的具体类型,所以您可以将其编写如下:

trait Fnord {
    fn do_it(&self) -> i32;
}

impl Fnord for i32 {
    fn do_it(&self) -> i32 {
        *self
    }
}

impl<'a> From<&'a i32> for &'a dyn Fnord {
    fn from(i: &'a i32) -> Self {
        i as _
    }
}

struct YourObject {
    v1: Vec<i32>,
    v2: Vec<i32>,
}

impl YourObject {
    fn iter_as<'a, T>(&'a self) -> impl Iterator<Item = T> + 'a
    where
        T: From<&'a i32>, // Add the other bounds you need
    {
        self.v1
            .iter()
            .map(|o| o.into())
            .chain(self.v2.iter().map(|o| o.into()))
    }
}

fn main() {
    let obj = YourObject {
        v1: vec![1, 2],
        v2: vec![3],
    };

    for s in obj.iter_as::<&dyn Fnord>() {
        println!("{}", s.do_it()); // 1 2 3
    }
}

借助宏,可以减少 From 实现样板:

macro_rules! impl_from_for_dyn_trait {
    ( $concrete:ty, $trait:path ) => {
        impl<'a> From<&'a $concrete> for &'a dyn $trait {
            fn from(c: &'a $concrete) -> Self {
                c as _
            }
        }
    }
}

impl_from_for_dyn_trait!(i32, Fnord);

关于generics - 泛型函数可以用特征参数化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60113932/

相关文章:

java - 在集合中使用 "precursor"类

generics - Java 数组协方差是否违反 Liskov 替换原则?

java - 在运行时获取列表对象的类型

rust - 在 Rust 中通过提前返回来处理错误的惯用方法

rust - 有没有办法只为 send_to() 创建一个没有 bind() 的 UdpSocket?

c++ - Traits 类作为模板模板参数

Scala asInstanceOf 泛型类型不会在 Try 中失败

python - 将 Python 列表传递给 Rust 函数

Groovy:继承特征方法

scala - 使用子类的类型实现特征方法