I am struggling a bit with generics, traits and return types.
Imagine a simple function like this. I can use impl
here to define
the return type.
fn retn_vec_iter(v:&Vec<isize>) -> impl Iterator<Item=&isize>{
v.iter()
}
Now imagine I want to define this as a trait.
trait Return {
fn retn_vec_iter<'a, I>(v:&'a Vec<isize>) -> impl Iterator<Item=&'a isize>;
}
I am not allowed to do this unfortunately.
error[E0562]: `impl Trait` not allowed outside of function and inherent method return types
--> src/main.rs:6:57
|
6 | fn retn_vec_iter<'a, I>(&self, v:&'a Vec<isize>) -> impl Iterator<Item=&'a isize>;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
So, I have tried this instead.
trait Return {
fn retn_vec_iter<'a, I>(&self, v:&'a Vec<isize>) -> I
where I: Iterator<Item=&'a isize>;
}
This compiles but if I try to implement it, it fails:
fn retn_vec_iter(v:&Vec<isize>) -> impl Iterator<Item=&isize>{
v.iter()
}
trait Return {
fn retn_vec_iter<'a, I>(&self, v:&'a Vec<isize>) -> I
where I: Iterator<Item=&'a isize>;
}
struct Empty;
impl Return for Empty {
fn retn_vec_iter<'a, I>(&self, v:&'a Vec<isize>) -> I
where I: Iterator<Item=&'a isize> {
retn_vec_iter(v)
}
}
as the generic version does not have the same return type as the bare
function retn_vec_iter
|
1 | fn retn_vec_iter(v:&Vec<isize>) -> impl Iterator<Item=&isize>{
| -------------------------- the found opaque type
...
13 | fn retn_vec_iter<'a, I>(&self, v:&'a Vec<isize>) -> I
| - this type parameter - expected `I` because of return type
14 | where I: Iterator<Item=&'a isize> {
15 | retn_vec_iter(v)
| ^^^^^^^^^^^^^^^^ expected type parameter `I`, found opaque type
|
= note: expected type parameter `I`
found opaque type `impl std::iter::Iterator`
I think I am doing something wrong here. How do I add a method to
trait that returns an iterator of some type?