How to convert an Option to an iterator of zero

2019-07-21 01:33发布

问题:

I'm trying to decode a digit to an integer and either get an iterator over just this digit or an empty iterator if it wasn't a digit. I tried to do it like that:

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

This doesn't compile. I get the following error message:

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<_>`

I there any way to tell the .unwrap_or(...) that I don't care of the actual type, but just that I will get an implementation of Iterator?

回答1:

The IntoIterator trait exists solely for the purpose of being able to convert types into iterators:

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 implements IntoIterator:

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

The same is true for Result.

All you need to do is call into_iter (or use the value in a place that calls IntoIterator like a for loop):

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

See also:

  • Why does `Option` support `IntoIterator`?
  • Iterator on Option<Vec<>>


标签: rust traits