I'm trying to store the result of a function that returns an Impl Iterator
in a struct. I think the only way is to use a generic type. Consider the following program:
struct Foo<'a, I: Iterator<Item = &'a u8>> {
inner: I,
}
struct Bar<'a> {
v: &'a [u8],
}
impl<'a> Bar<'a> {
fn numbers(&self) -> impl Iterator<Item=&'a u8> {
self.v.iter().filter(|&&x| x!= 4)
}
}
impl<'a, I: Iterator<Item = &'a u8>> Iterator for Foo<'a, I> {
type Item=&'a u8;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next()
}
}
impl<'a, I: Iterator<Item = &'a u8>> Foo<'a, I> {
fn new(a: I) -> Foo<'a, I> {
Foo { inner: a }
}
fn new2(a: &Bar) -> Foo<'a, I> {
let v = a.numbers();
Foo { inner: v }
}
}
fn main() {
let values = vec![0,1,2,3,4,5,6];
let bar = Bar { v: values.as_slice()};
let foo = Foo::new(bar.numbers());
println!("{:?}", foo.collect::<Vec<_>>());
//this errors
let foo = Foo::new2(&bar);
println!("{:?}", foo.collect::<Vec<_>>());
//this works
let num = bar.numbers();
let foo = Foo { inner: num };
println!("{:?}", foo.collect::<Vec<_>>());
}
This program doesn't compile because of an error in Foo::new2
error[E0308]: mismatched types
--> src/main.rs:29:22
|
29 | Foo { inner: v }
| ^ expected type parameter, found anonymized type
|
= note: expected type `I`
found type `impl std::iter::Iterator`
But when I do the same assignment in main
it does work. Is there a reason for this behavior?