#Associated type for opaque return type

2 messages · Page 1 of 1 (latest)

hollow stream
#

I keep running into this problem so finally asking about it rather than finding weird work arounds.
I have a trait with an associated type with a given iterator bound.
The type I am implementing the trait for has a useful method that returns an opaque iterator type.
Is there any way to transitively associate that return type with the associated type?
e.g.

struct Foo(usize);
impl Foo {
    fn iter_range(&self) -> impl Iterator<Item = usize> {
        let count = self.0;
        std::iter::from_fn(move || {
            if count == 0 {
                None
            } else {
                let rv = Some(count);
                count -= 1;
                rv
            }
        })
    }
}
trait Bar {
    type Iter: Iterator<Item = usize>;
    fn iter_bar(&self) -> Self::Iter;
}
impl Bar for Foo {
    type Iter; // what to do here
    fn iter_bar(&self) -> Self::Iter {
        self.iter_range()
    }
}

Note that Foo is a foreign type and Bar is my trait in my use case.
Additionally Box<dyn Iterator<Item = usize>> is a solution, but this seems to be an unnecessary allocation when the iterator can be used anywhere other than the trait without the extra allocation.

stray nexus
#

I'm pretty sure your only options are to use the nightly type_alias_impl_trait or to change Foo to return a concrete type.