如何使用以迭代器为参数的方法进行动态调度?

How to use dynamic dispatch with a method which takes an iterator as a parameter?

我正在用 Rust 编写一个命令行应用程序来处理来自传感器的音频。我希望用户能够从多个选项中选择要应用的算法或过滤器。我希望使用动态调度来切换出一个在运行时实现我的过滤器特征的结构。但是,编译器不允许这样做,因为其中一个特征方法采用通用参数。

我怎样才能实现同样的功能,而不引起任何编译器问题?我知道一个简单的解决方案是将 process 方法的参数更改为数组或向量,但这是我最后的选择,因为我更愿意采用迭代器或 IntoIterator,因为它更通用,更适合我的具体需求。

下面是一些演示问题的代码。

trait SensorFilter {
    fn process(&self, sig: &mut impl Iterator<Item = f32>) -> Vec<f32>;
}

struct Alg1 {
    mul: f32,
}

struct Alg2 {
    add: f32,
}

impl SensorFilter for Alg1 {
    fn process(&self, sig: &mut impl Iterator<Item = f32>) -> Vec<f32> {
        sig.map(|x| x * self.mul).collect()
    }
}

impl SensorFilter for Alg2 {
    fn process(&self, sig: &mut impl Iterator<Item = f32>) -> Vec<f32> {
        sig.map(|x| x * self.add).collect()
    }
}

enum AlgChoice {
    Alg1,
    Alg2
}

fn main() {
    let choice = AlgChoice::Alg1; // user chooses via command-line.
    let mut sig = vec![0.,1.,2.,3.,4.,5.,6.].into_iter(); // iterator gets data from sensor.

    // This doesn't work, because my trait cannot be made into an object.
    let alg: &dyn SensorFilter = match choice {
        AlgChoice::Alg1 => Alg1{mul:0.3},
        _ => Alg2{add:1.2},
    };

    let result = alg.process(&mut sig);
    println!("{:?}",result);
}

谢谢:)

这里的技巧是将通用函数参数更改为通用特征参数:

// Make the generic param into a type argument w/ constraints
trait SensorFilter<I> where I: Iterator<Item = f32> {
    fn process(&self, sig: &mut I) -> Vec<f32>;
}

struct Alg1 {
    mul: f32,
}

struct Alg2 {
    add: f32,
}

// Implement trait for all I that match the iterator constraint
impl<I: Iterator<Item = f32>> SensorFilter<I> for Alg1 {
    fn process(&self, sig: &mut I) -> Vec<f32> {
        sig.map(|x| x * self.mul).collect()
    }
}

impl<I: Iterator<Item = f32>> SensorFilter<I> for Alg2 {
    fn process(&self, sig: &mut I) -> Vec<f32> {
        sig.map(|x| x * self.add).collect()
    }
}

enum AlgChoice {
    Alg1,
    Alg2
}

fn main() {
    let choice = AlgChoice::Alg1; // user chooses via command-line.
    let mut sig = vec![0.,1.,2.,3.,4.,5.,6.].into_iter(); // iterator gets data from sensor.

    // Specify the type argument of your trait.
    let alg: &dyn SensorFilter<std::vec::IntoIter<f32>> = match choice {
        AlgChoice::Alg1 => &Alg1{mul:0.3},
        _ => &Alg2{add:1.2}, 
    };

    let result = alg.process(&mut sig);
    println!("{:?}",result);
}

使 SensorFilter 对象安全的最简单方法是简单地将 process 更改为接受 dyn Iterator 而不是 impl Iterator:

trait SensorFilter {
    fn process(&self, sig: &mut dyn Iterator<Item = f32>) -> Vec<f32>;
}

如果你不能这样做,例如因为 Iterator 实际上是 non-object-safe,你可以改为提取公共的 non-object-safe 部分到第二个特征中,并实现它自动为所有 SensorFilter:

// This trait is object-safe.
trait SensorFilter {
    fn filter(&self, x: f32) -> f32;
}

// This trait will not be object-safe because it uses generics.
trait Process {
    fn process<I: IntoIterator<Item = f32>>(&self, sig: I) -> Vec<f32>;
}

// The `?Sized` bound allows you to call `.process()` on `dyn SensorFilter`.
impl<T: ?Sized + SensorFilter> Process for T {
    fn process<I: IntoIterator<Item = f32>>(&self, sig: I) -> Vec<f32> {
        sig.into_iter().map(|x| self.filter(x)).collect()
    }
}

// ...

impl SensorFilter for Alg1 {
    fn filter(&self, x: f32) -> f32 {
        x * self.mul
    }
}

impl SensorFilter for Alg2 {
    fn filter(&self, x: f32) -> f32 {
        x * self.add
    }
}

Playground

请注意,我使用的是 IntoIterator 而不是 Iterator,这更笼统。

这个想法的一个变体,当你不能轻易地从 SensorFilter 中删除通用性时,是使用双重分派:写 SensorFilter 来使用 dyn Iterator 而不是 impl Iterator,然后写一个方便的特征,用特定类型包装它:

trait SensorFilter {
    fn process_dyn(&self, sig: &mut dyn Iterator<Item = f32>) -> Vec<f32>;
}

trait Process {
    fn process<I: IntoIterator<Item = f32>>(&self, sig: I) -> Vec<f32>;
}

impl<T: ?Sized + SensorFilter> Process for T {
    fn process<I: IntoIterator<Item = f32>>(&self, sig: I) -> Vec<f32> {
        self.process_dyn(&mut sig.into_iter())
    }
}