Mismatch between associated type and type parameter only when impl is marked `default`

前端 未结 1 951
别那么骄傲
别那么骄傲 2021-01-17 19:08

The following code results in an error (Playground)

#![feature(specialization)]

trait Foo {
    type Assoc;
    fn foo(&self) -> &Self::Assoc;
}
         


        
相关标签:
1条回答
  • 2021-01-17 19:51

    The Specialization feature is showing no signs of stabilising, mostly because of soundness concerns, so you should expect some problems.

    You have this:

    #![feature(specialization)]
    
    trait Foo {
        type Assoc;
        fn foo(&self) -> &Self::Assoc;
    }
    
    default impl<T> Foo for T {
        type Assoc = T;
        fn foo(&self) -> &Self::Assoc {
            self
        }
    }
    

    But imagine that you added another implementation with its own associated type but without implementing foo. This implementation's foo will be "inherited" from the other, less specific, implementation:

    impl<T: SomeConstraint> Foo for T {
        type Assoc = NotT;
    }
    

    Then there'd be a problem. Your foo would be returning a T but, whenever T is SomeConstraint there'd be a type mismatch because it should be returning a NotT.

    RFC 2532 — associated type defaults mentions a possible solution in its Future Work section. A hypothetical default block could be used to indicate that associated type(s) and method(s) would need to be specialized together. There's no sign of when such a feature would be considered for inclusion, however.

    0 讨论(0)
提交回复
热议问题