Search code examples
typesrusthigher-kinded-types

Can a trait have a supertrait that is parameterized by a generic?


Can you do something like this in Rust?

trait A : forall<T> B<T> { ... }

That is, if we want:

impl A for D { ... }

We must first implement:

impl<T> B<T> for D { ... }

Solution

  • No. Rust's type system doesn't currently support any features involving higher kinded types. It does, however, support a similar construction to what you described, but limited to lifetime parameters. For example:

    trait B<'a> {}
    
    trait A: for<'a> B<'a> {}
    
    struct D;
    
    impl A for D { }
    

    This is an error:

    error[E0277]: the trait bound `for<'a> D: B<'a>` is not satisfied
     --> src/lib.rs:7:6
      |
    7 | impl A for D { }
      |      ^ the trait `for<'a> B<'a>` is not implemented for `D`
    

    Until you add the blanket implementation:

    impl<'a> B<'a> for D { }
    

    It's not impossible that Rust will eventually add similar functionality for types too, but I wouldn't expect it any time soon.