Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 569
盛安安 Avatar asked Jan 24 '15 07:01

盛安安


1 Answers

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`
    }
}
like image 158
huon Avatar answered Nov 19 '22 23:11

huon