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

≡放荡痞女 提交于 2019-12-14 03:54:01

问题


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


来源:https://stackoverflow.com/questions/51662730/how-to-convert-an-optiont-to-an-iterator-of-zero-or-one-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!