1
votes

I cannot figure out why this will not compile. I just want to have a struct with an iterator where the iterator is created with a function that returns impl Trait. I changed my code to a minimal example for this post.

Open in Rust Playground

struct Foo {
    pub it: Option<Box<dyn Iterator<Item=i32>>>,
}

impl Foo {
    fn new() -> Self {
        let it = Some(Box::new(my_numbers()));
        Self { it: it }
    }
}

fn my_numbers() -> impl Iterator<Item=i32> {
    1..10
}

Compiler output:

   |
8  |         Self { it: it }
   |                    ^^ expected trait object `dyn std::iter::Iterator`, found opaque type
...
12 | fn my_numbers() -> impl Iterator<Item=i32> {
   |                    ----------------------- the found opaque type
   |
   = note: expected enum `std::option::Option<std::boxed::Box<(dyn std::iter::Iterator<Item = i32> + 'static)>>`
              found enum `std::option::Option<std::boxed::Box<impl std::iter::Iterator>>`

Edit:

I found one workaround is using #![feature(type_alias_impl_trait)], but this is not stable.

1

1 Answers

1
votes

Casting the boxed value, i.e. Box::new(my_numbers()) as Box<dyn Iterator<Item=_>> solves this with stable Rust 1.41.0. It's possible that enabling type_alias_impl_trait helps with this missing type inference aspect.