Problems with associated type, trait an lifetime


#1

Why this code gives error? Is it a bug?

Without lifetime or Iter it compiles.

trait T<'a> {
    type A;
    type Iter: Iterator<Item=Self::A>;
    fn new() -> Self;

    fn iter(&self) -> Self::Iter;
    
    fn test() where Self: Sized {
        let a = <Self as T<'a>>::new();
        let _ = a.iter().map(|a| a);
    }
}

fn main() {}

#2

This works: http://is.gd/JD9dzH


#3

Thanks, it solved my problem. Do you think that it is a bug? It strange that without Iter it works too.


#4

I’m not sure what’s the real reason here, but I guess that’s because the new() method requires concrete type to choose implementation, and as trait T is parametrized by lifetime parameter, it needs some to complete the type instance. In the snippet above I used already defined lifetime parameter 'a defined for trait definition at hand. When I tried to use another lifetime by introducing it in method signature (fn test<'a>()) it didn’t work as well. Lifetime placeholder '_ didn’t work either, only concrete lifetime 'a known by the trait worked.


#5

I modified the example to include a call to iter followed by a map. The error returned… It’s strange.


#6

This works:
https://play.rust-lang.org/?gist=a2b9f5461c46cb436775&version=stable

I think the problem is that the compiler seems to think you’ve made Self::Iter higher ranked by bounding it as having Item == Self::A. It seems to mistakenly think that Self is higher ranked in this context.