Superfluous lifetime 'b in function parameter - expecting compiler error

fn longest<'a, 'b>(s1: &'a str, s2: &'a str) -> &'a str {
    if s1.len() > s2.len() {
        &s1
    } else {
        &s2
    }
}
fn main() {
    let x = longest("aaaa", "bbb");
    dbg!(x);
}

The 'b lifetime is not used since the references s1 and s2 have the same lifetime 'a.

The 'b lifetime parameter is unnecessary and can be removed without affecting the functionality of the code.

I was expecting an error - remove lifetime 'b ...

is there a reason why compiler allows a superfluous lifetime 'b or this is a compiler missing error bug?

it's like unused variable, it's unnecessary, but harmless. you can use clippy to check this kind of lint.

You don't do so here, but there's nothing that says the body of the function can't make use of it's generic parameters even when they aren't used in the inputs or outputs. For example.

For all the compiler knows, you have some future use planned for the currently unused parameter.


That said, I could see a warn-by-default lint in this case, as there's not a whole lot you can do with unconstrained lifetime not used in the inputs or outputs.

yes, clippy is flagging this correctly:

❯ cargo clippy
    Checking hello_world v0.1.0 (/Volumes/T7/trash/2023_04_28/hello_world)
warning: this lifetime isn't used in the function definition
 --> src/main.rs:1:16
  |
1 | fn longest<'a, 'b>(s1: &'a str, s2: &'a str) -> &'a str {
  |                ^^
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#extra_unused_lifetimes
  = note: `#[warn(clippy::extra_unused_lifetimes)]` on by default

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.