Lifetime parameter never used except in defining trait bound

I'm trying to create a struct that has a field with an Option<W> where W implements some trait that requires an explicit lifetime.

trait MyTrait<'a> {
    fn foo(self, input: &'a str) -> Self;

struct MyStruct<'a, W> 
    W: MyTrait<'a>
    w: Option<W>

This creates an error of

parameter 'a is never used: unused parameter

but it is used in the trait bound. How do I get around this?

'a isn't used directly in the struct. In general when you have this kind of issue, PhantomData is the answer.

Don't put unnecessary trait bounds on your types, move the MyTrait<'a> bound to where it is actually used

@KrishnaSannasi, what do you mean by that? I don't believe I'm allowed to put a trait bound in the field definition like

struct MyStruct<'a> {
    w: Option<W: MyTrait<'a>>
struct MyStruct<W> {
    w: Option<W>

impl<W> MyStruct<W> {
    fn call_foo<'a>(self, input: &'a str) -> Self
    where W: MyTrait<'a> {
        // ...

Putting trait bounds on your types leads to trait bounds everywhere, and it quickly becomes unmanageable

1 Like