Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type annotations required in the context of associated types an iterators

Tags:

rust

I have created a minimal example illustrating a type inference problem that I unable to solve.

trait A<'a> {
    type Item: Copy;
    type Iter: Iterator<Item=Self::Item>;

    fn items(&'a self) -> Self::Iter;

    fn consume(&'a self, i: Self::Item) -> Self::Item;

    fn f(&'a self) {
        let _ = self.items().map(|i| self.consume(i) as Self::Item);
    }
}

The compiler error is

x.rs:10:30: 10:68 error: type annotations required: cannot resolve `<<Self as A<'_>>::Iter as core::iter::Iterator>::Item == _` [E0284]
x.rs:10         let _ = self.items().map(|i| self.consume(i) as Self::Item);

I have looked other questions about requiring type annotations but this seems to be a particular case involving associated types.

like image 659
malbarbo Avatar asked Aug 04 '15 13:08

malbarbo


1 Answers

I think this is #24338, and is caused by the compiler getting confused by the lifetime in the trait and the associated type. It can be worked around by moving the body of the f method into a separate function (nested counts as separate, since they're type checked independently):

trait A<'a> {
    // ...

    fn f(&'a self) {
        f_body(self);

        fn f_body<'a, T: ?Sized + A<'a>>(x: &'a T) {
            let _ = x.items().map(|i| x.consume(i) as T::Item);
        }
    }
}
like image 168
huon Avatar answered Sep 23 '22 03:09

huon