Is there any way to work around an unused type par

2019-06-18 02:06发布

问题:

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.

回答1:

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`
    }
}