Skip to content

Add lint to detect lifetime parameters that could be replaced by 'static #120344

Open
@oskgo

Description

@oskgo

Code

pub fn foo<'a>() -> &'a i32 {&0}

Current output

empty

Desired output

warning: lifetime parameter `'a` is unnecessary
 --> src/lib.rs:1:12
  |
1 | pub fn foo<'a>() -> &'a i32 {&0};
  |            ^^ unnecessary lifetime parameter
  |
  = help: consider removing `'a`, using `'static` instead

Rationale and extra context

In some cases lifetime parameters might as well be 'static because of subtyping. Using a 'static lifetime can simplify the signature by avoiding generics and help teach beginners that the only reason this works is because of static promotion. Adding something about static promotion to the warning could also make sense. I'm not too happy with my "desired output".

This is also related to the unused_lifetimes lint, but that doesn't catch this either and it's not exactly "unused".

Credit goes to @estebank for the suggestion in #48998 (comment)

Other cases

No response

Rust Version

rustc 1.75.0 (82e1608df 2023-12-21)
binary: rustc
commit-hash: 82e1608dfa6e0b5569232559e3d385fea5a93112
commit-date: 2023-12-21
host: x86_64-pc-windows-msvc
release: 1.75.0
LLVM version: 17.0.6

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lifetimesArea: Lifetimes / regionsA-lintsArea: Lints (warnings about flaws in source code) such as unused_mut.C-feature-requestCategory: A feature request, i.e: not implemented / a PR.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-langRelevant to the language team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions