Trait parametrization is not carrying through ... Example self explanatory


#1
struct X();

trait Y<'a> {
    fn nuthing(x: &'a X);
}

struct Z<'a, T>
where
    T: Y<'a>,
{
    t: T,
}

fn main() {}

(Playground)


#2

You should at least quote the given error, so people can see it without going to the playground.

error[E0392]: parameter `'a` is never used
 --> src/main.rs:7:10
  |
7 | struct Z<'a, T>
  |          ^^ unused type parameter
  |
  = help: consider removing `'a` or using a marker such as `std::marker::PhantomData`

error: aborting due to previous error

AIUI all type parameters must be used within the type, not just in its where constraints. You can add something like marker: PhantomData<&'a X> to the struct to “use” it. This is a zero-sized type, so the struct’s overall size will not increase from this.


#3

To add to @cuviper, you may also use an HRTB:

struct Z<T>
where
    T: for<'a> Y<'a>,
{
    t: T,
}

The right solution would depend on your real case as this example is (rightfully and necessarily so) too contrived.


#4

yes, HRTB was the black magic necessary here since doing PhantomData nails the lifetime and the parameter cannot be used on e.g. held object that tries to use the type with shorter lifetime … Discusison on channel with @chaltas helped …