【问题标题】:A parameter that accepts a sequence of trait objects and iterate through it multiple times in Rust一个接受一系列特征对象并在 Rust 中多次迭代的参数
【发布时间】:2021-04-28 00:04:07
【问题描述】:

我有一个函数,它接受一系列特征对象并多次迭代它,例如,

trait Animal {
    fn make_noise(&self);
}

fn make_lots_of_noises(animals: &[&dyn Animal]) {
    animals.iter().for_each(|animal| animal.make_noise());
    animals.iter().for_each(|animal| animal.make_noise());
    animals.iter().for_each(|animal| animal.make_noise());
}

但我希望该函数能够对借用和拥有的数据结构进行操作。以下是我尝试过的选项:

&[&dyn Animal] 如代码片段所示。问题:如果我拥有 trait 对象,例如 animals: &[Box<dyn Animal>],那么我必须调用 make_lots_of_noises(animals.map(Box::as_ref).collect::<Vec<_>>().as_slice(),这涉及到堆上不必要的分配。

&[&R] where R: AsRef<dyn Animal> + ?Sized。问题:T 没有实现AsRef<T>!它现在适用于各种智能指针,但不适用于&[&dyn Animal]

【问题讨论】:

    标签: rust iterator trait-objects


    【解决方案1】:

    使用Borrow trait,它确实有你想要的impl Borrow<T> for T

    use std::borrow::Borrow;
    
    trait Animal {
        fn make_noise(&self);
    }
    
    struct Mouse;
    impl Animal for Mouse {
        fn make_noise(&self) { /* squeak */ }
    }
    
    fn make_lots_of_noises<A: Borrow<dyn Animal>>(animals: &[A]) {
        animals.iter().for_each(|animal| animal.borrow().make_noise());
        animals.iter().for_each(|animal| animal.borrow().make_noise());
        animals.iter().for_each(|animal| animal.borrow().make_noise());
    }
    
    fn main() {
        make_lots_of_noises(&[&Mouse as &dyn Animal]);
        make_lots_of_noises(&[Box::new(Mouse) as Box<dyn Animal>]);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-13
      • 1970-01-01
      相关资源
      最近更新 更多