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

How to convert an Option<T> to an iterator of zero or one element?

我正在尝试将一个数字解码为一个整数,或者获取一个仅针对该数字的迭代器,或者如果它不是一个数字则获取一个空迭代器。我试着这样做:

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?

的实现

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

Conversion into an Iterator.

By implementing IntoIterator for a type, you define how it will be converted to an iterator. This is common for types which describe a collection of some kind.

One benefit of implementing IntoIterator is that your type will work with Rust's for loop syntax.

How to convert an Option<T> to an iterator of zero or one element?

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(或在像 for 循环一样调用 IntoIterator 的地方使用该值):

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

另请参阅:

  • Why does `Option` support `IntoIterator`?