Search code examples
rusttraitstype-parameter

Is there any way to work around an unused type parameter?


Code:

trait Trait<T> {}

struct Struct<U>;

impl<T, U: Trait<T>> Struct<U> {}

Error:

error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates
 --> src/main.rs:5:6
  |
5 | impl<T, U: Trait<T>> Struct<U> {}
  |      ^ unconstrained type parameter

It seems that RFC 447 prohibits this pattern; is there any way to work around this? I think it could be solved by changing T to an associated type, but that would prevent me from doing multidispatch.


Solution

  • A type parameter that's unused in the struct can use PhantomData:

    struct Struct<U> {
        _marker: PhantomData<U>,
    }
    
    impl<U> Struct<U> {
        fn example<T>(&self)
        where
            U: Trait<T>,
        {
            // use `T` and `U`
        }
    }