0

I have a function which consumes an iterator:

fn func<T: iter::Iterator<Item = char>>(i: T) {
    //...   
}

I need to write a function whose input is an Option<char> (type char is not important here, just for illustrative purpose), and depends on the value of input, it should create an empty or an once iterator. My solution is: use std::iter;

fn option_iter(input: Option<char>) {
    let i: Box<iter::Iterator<Item = char>> = if let Some(input) = input {
        Box::new(iter::once(input))
    } else {
        Box::new(iter::empty())
    };
}

I find this ugly because of type erasure by Box. I cannot use:

let i = if let Some(input) = input {
    iter::once(input)
} else {
    iter::empty()
};
func(i);

because the compiler complains the types of two branches are different. Is there any method which does not use Box for this situation?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Ta Thanh Dinh
  • 638
  • 1
  • 5
  • 12
  • 1
    If you can change `func` to take `IntoIterator` instead of `Iterator`, you can just write `func(input)`. Also, `Iterator` is in the prelude, so you don't need to `use std::iter;` first. – trent Aug 17 '18 at 14:11

1 Answers1

3

Option has an iter method that does what you want.

Jmb
  • 18,893
  • 2
  • 28
  • 55