是否可以从取决于参数的特征返回特征?

时间:2019-11-06 16:53:58

标签: rust iterator traits

我在Iteratorplayground)上有两个运算符

fn begins_with<'a, I>(lines: I, query: &'a str) -> impl Iterator<Item = String> + 'a
where
    I: Iterator<Item = String> + 'a,
{
    // Some whatever filtering
    lines.filter(move |line| line.starts_with(&query))
}

fn whatever<'a, I>(lines: I, query: &'a str) -> impl Iterator<Item = String> + 'a
where
    I: Iterator<Item = String> + 'a,
{
    // Some whatever operation
    let mut sorted: Vec<String> = lines.collect();
    sorted.sort_unstable();
    sorted.into_iter().map(|s| s.to_lowercase())
}

我希望能够使用其中一个并将其应用于String的迭代器上

一种可能性是像这样(playground)使用enum

pub enum Operator {
    BeginsWith,
    Whatever,
}

fn operate<'a, I>(operator: Operator, lines: I, query: &'a str) -> impl Iterator<Item = String> + 'a
where
    I: Iterator<Item = String> + 'a,
{
    match operator {
        Operator::BeginsWith => begins_with(lines, query),
        Operator::Whatever => whatever(lines, query),
    }
}

但是我收到以下错误(很公平)

error[E0308]: match arms have incompatible types
  --> src/lib.rs:30:31
   |
28 | /     match operator {
29 | |         Operator::BeginsWith => begins_with(lines, query),
   | |                                 ------------------------- this is found to be of type `impl std::iter::Iterator`
30 | |         Operator::Whatever => whatever(lines, query),
   | |                               ^^^^^^^^^^^^^^^^^^^^^^ expected opaque type, found a different opaque type
31 | |     }
   | |_____- `match` arms have incompatible types
   |
   = note: expected type `impl std::iter::Iterator` (opaque type)
              found type `impl std::iter::Iterator` (opaque type)

另一种方法是制作特征并实现它(playground):

pub trait Operator {
    pub fn operate<'a, I>(lines: I, query: &'a str) -> impl Iterator<Item = String> + 'a
where
    I: Iterator<Item = String> + 'a;
}

但这在Rust中是不允许的。

Rust为我提供了什么机制来返回Iterator,该机制取决于传递给从特征实现的方法中的参数?

0 个答案:

没有答案
相关问题