11

I have a fun one, where the compiler says I have an unused lifetime parameter, except it's clearly used. It feels almost like a compiler error, though I'm probably overlooking something? Who can see the mistake?

main.rs

trait Context<'a> {
    fn name(&'a self) -> &'a str;
}

type Func<'a, C: Context<'a>> = dyn Fn(C);

pub struct BuiltInFunction<'a, C: Context<'a>> {
    pub(crate) func: Box<Func<'a, C>>,
}
error[E0392]: parameter `'a` is never used
 --> src/main.rs:7:28
  |
7 | pub struct BuiltInFunction<'a, C: Context<'a>> {
  |                            ^^ unused parameter
  |
  = help: consider removing `'a`, referring to it in a field, or using a marker such as `PhantomData`

For more information about this error, try `rustc --explain E0392`.
error: could not compile `lifetime-test` (bin "lifetime-test") due to 1 previous error
top 5 comments
sorted by: hot top controversial new old
[-] notriddle@programming.dev 18 points 7 months ago

The warning is in the wrong place, but it's real.

The actual problem is on line 5, where you have a type alias that doesn't use the lifetime parameter. The warning ought to be there, but rustc expands type aliases in place, so it doesn't check there.

The compiler should be able to fix it by not expanding type aliases directly in place. https://github.com/rust-lang/rust/issues/112792

[-] arendjr@programming.dev 8 points 7 months ago

Ahh, that's good to know! Thanks, together with @taladar@sh.itjust.works fix that resolves it :+1:

[-] taladar@sh.itjust.works 11 points 7 months ago* (last edited 7 months ago)

Well, you aren't using it on the right side of Func and only using it as a parameter to that in BuiltInFunction. You can probably use C: for<'a> Context<'a> instead in the parameter lines?

[-] arendjr@programming.dev 6 points 7 months ago

Thanks, that solves it indeed!

[-] jlh@lemmy.jlh.name 1 points 7 months ago

I think you might not be allowed to use two 'a s in one type? I could be wrong though, I'm not very familiar with lifetimes.

this post was submitted on 23 Mar 2024
11 points (92.3% liked)

Rust

5974 readers
64 users here now

Welcome to the Rust community! This is a place to discuss about the Rust programming language.

Wormhole

!performance@programming.dev

Credits

  • The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)

founded 1 year ago
MODERATORS