如何将Option <t>转换为零或一个元素的迭代器?

时间:2018-08-02 22:01:33

标签: rust traits

我正在尝试将一个数字解码为整数,并获得一个仅对此数字进行迭代的迭代器,或者如果不是数字则获取一个空的迭代器。我试图那样做:

let ch = '1';
ch.to_digit(10).map(once).unwrap_or(empty())

这不能编译。我收到以下错误消息:

error[E0308]: mismatched types
 --> src/lib.rs:6:41
  |
6 |     ch.to_digit(10).map(once).unwrap_or(empty());
  |                                         ^^^^^^^ expected struct `std::iter::Once`, found struct `std::iter::Empty`
error[E0308]: mismatched types
 --> src/lib.rs:6:41
  |
6 |     ch.to_digit(10).map(once).unwrap_or(empty());
  |                                         ^^^^^^^ expected struct `std::iter::Once`, found struct `std::iter::Empty`
  |
  |
  = note: expected type `std::iter::Once<u32>`
             found type `std::iter::Empty<_>`

  = note: expected type `std::iter::Once<u32>`
             found type `std::iter::Empty<_>`

我有什么办法告诉.unwrap_or(...)我不在乎实际的类型,只是我将得到Iterator的实现?

1 个答案:

答案 0 :(得分:3)

IntoIterator特征的存在仅是为了能够将类型转换为迭代器:

  

转换为迭代器。

     

通过为类型实现IntoIterator,您可以定义如何将其转换为迭代器。这对于描述某种类型的集合的类型很常见。

     

实现IntoIterator的一个好处是您的类型将会 work with Rust's for loop syntax

  

如何将Option<T>转换为零或一个元素的迭代器?

Option实现IntoIterator

impl<'a, T> IntoIterator for &'a mut Option<T>
impl<T> IntoIterator for Option<T>
impl<'a, T> IntoIterator for &'a Option<T>

Result也是如此。

您需要做的就是调用into_iter(或在像IntoIterator循环那样调用for的地方使用该值)

fn x() -> impl Iterator<Item = u32> {
    let ch = '1';
    ch.to_digit(10).into_iter()
}

另请参阅: