Compiler thinks that lifetime parameter is unused

I just ran into the following issue:

If you compile this, you get the error
parameter 'a is never used


trait Bar<'a> { }

struct Foo<'a, T>
where T: Bar<'a> {
    value: T,
}


(Playground)

But when I remove the 'a, it throws missing lifetime specifier and suggests using the 'a.

I'm assuming I ran into a bug, but I don't know rust too well, that I can be sure about that. Maybe I'm misunderstanding something.
Whats your opinion?

Rust wants a field using the parameter, I think in part because it needs to determine the variance. You can add a field like PhantomData<&'a ()> to cover this.

1 Like

Or better yet, don't put unnecessary bounds in thr type definition. Instead put the bounds where the type is used bound is used, usually near the relevant methods.

3 Likes

Hmm I should have stated, that I ran into the problem while using the crate Logos.
I wanted to write the following:

pub struct ParserToken<'source, Token>
where Token: Logos<'source> {
    token: Token,
    span: Span,
    slice: String
}

But @cuviper 's approach did the trick. Although I don't quite like to pollute my struct with that ^^

Thanks guys :slight_smile:

Yeah, you can almost always move the bound later.

In this case you can move the bound to where you parse out each token

1 Like

So how can I achieve that?

pub struct ParserToken<Token> {
    token: Token,
    span: Span,
    slice: String
}

impl<Token> ParserToken<Token> {
    fn parse_token<'source>(text: &'source str) -> Self
    where Token: Logos<'source> {
        ...
    }
}

Something like this, you may need to adapt parse_token's signature to your use-case

2 Likes

Ah okay, got it :slight_smile:

Thank you very much!

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.