3

Given the following code:

use std::iter::Iterator;

trait Sequence {
    type SeqType: Iterator<Item = u32>;

    fn seq(&self) -> Option<Self::SeqType>;
}

struct Doubler<'a>(Option<&'a [u32]>);

impl<'a> Sequence for Doubler<'a> {
    type SeqType = Box<dyn Iterator<Item = u32>>;

    // NOT WORKING
    fn seq(&self) -> Option<Self::SeqType> {
        self.0
            .map(|v| Box::new(v.to_vec().into_iter().map(|x| x * 2)))
    }
}

fn print_seq<S: Sequence>(seq: S) {
    let v: Option<Vec<u32>> = seq.seq().map(|i| i.collect());
    println!("{:?}", v);
}

fn main() {
    let v = vec![1, 2, 3, 4];
    print_seq(Doubler(Some(&v)));
}

The compiler will complain with:

error[E0308]: mismatched types
  --> src/main.rs:16:9
   |
15 |       fn seq(&self) -> Option<Self::SeqType> {
   |                        --------------------- expected `std::option::Option<std::boxed::Box<(dyn std::iter::Iterator<Item = u32> + 'static)>>` because of return type
16 | /         self.0
17 | |             .map(|v| Box::new(v.to_vec().into_iter().map(|x| x * 2)))
   | |_____________________________________________________________________^ expected trait object `dyn std::iter::Iterator`, found struct `std::iter::Map`
   |
   = note: expected enum `std::option::Option<std::boxed::Box<(dyn std::iter::Iterator<Item = u32> + 'static)>>`
              found enum `std::option::Option<std::boxed::Box<std::iter::Map<std::vec::IntoIter<u32>, [closure@src/main.rs:17:58: 17:67]>>>`

But it works by replacing seq:

fn seq(&self) -> Option<Self::SeqType> {
    fn convert(s: &[u32]) -> Box<dyn Iterator<Item = u32>> {
        Box::new(s.to_vec().into_iter().map(|x| x * 2))
    }
    self.0.map(convert)
}

The code can be tested here.

The only difference is that a closure is used in the failing example, while the other uses a (named?) function, but the logic is the same. It seems like a lifetime problem but haven't been able to figure it out. Also, Option::map is supposed to eagerly consume the value, then the closure should be immediately used.

Why does the closure example fail?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Rodolfo
  • 335
  • 1
  • 4
  • 10
  • It looks like your question might be answered by the answers of [Use Option::map to Box::new a trait object does not work](https://stackoverflow.com/q/48864045/155423) and [How does the mechanism behind the creation of boxed traits work?](https://stackoverflow.com/q/52288980/155423). If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Oct 20 '20 at 16:55
  • 1
    You can fix the `map` example by [adding `as _` to tell the compiler where to add the coercion](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=f77c194069be98e06bb967c96d79d6b9). – trent Oct 20 '20 at 16:58
  • So, there's an implicit coercion that I never knew of. Thanks Shepmaster and trentcl – Rodolfo Oct 20 '20 at 18:52

0 Answers0