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