Reputation: 11730
I have some type with an iterator. The iterator has a generic functionality, so it takes a function as a parameter.
struct Foo {
...
}
impl Foo {
fn iter(&self) -> FooIterator<impl Fn(A) -> B> {
FooIterator {
f: |a| get_b(a),
}
}
}
struct FooIterator<F: Fn(A) -> B> {
f: F,
...
}
impl<F> Iterator for FooIterator<F> {
...
}
This is fine, but if I want to use my type in a for
loop, I need to implement IntoIterator
.
impl IntoIterator for &Foo {
type Item = ...;
type IntoIter = FooIterator<?>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
The question is, what can I write in place of the ?
? impl Fn(A) -> B
doesn't work, because impl traits are only available for function arguments and return types. It might be usable as an unstable feature, but in stable Rust it is not.
I could make this work with dynamic allocation.
impl IntoIterator for &Foo {
type Item = ...;
type IntoIter = Box<dyn Iterator<Item = Self::Item>>;
fn into_iter(self) -> Self::IntoIter {
Box::new(self.iter())
}
}
This works, but is there any way to do this without dynamic allocation?
Upvotes: 0
Views: 53