Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unifying an invariant lifetime with a covariant one is almost always bad #12657

Open
cbiffle opened this issue Apr 9, 2024 · 1 comment
Open
Labels
A-lint Area: New lints

Comments

@cbiffle
Copy link

cbiffle commented Apr 9, 2024

What it does

Triggers on code of the form &'a mut Something<'a>. (The mut is important here.) I see people write this when they're not sure what to put in each lifetime position, but it's (as far as I can tell!) basically always wrong, and causes weird lifetime errors in other places by unifying the two lifetimes. This is particularly annoying when it appears as a function argument, as it causes weird errors in the caller.

Unless I've missed something this code should almost always be &'b mut Something<'a> instead.

You'd probably also want this to point out cases of &'a mut &'a Something.

Advantage

Avoids unifying the invariant lifetime of the mut reference with the (often covariant) lifetime of the (often not mut) reference inside the parameterized type.

More importantly, avoids distant confusing errors from rustc attempting to solve lifetime constraints in callers.

Drawbacks

It's possible that this pattern has a use and I've never seen it -- if it does, this would false positive on such code.

Example

&'a mut Something<'a>

Could be written as:

&'b mut Something<'a>
@cbiffle cbiffle added the A-lint Area: New lints label Apr 9, 2024
@jendrikw
Copy link
Contributor

Adding some search terms:

indefinite borrow forever suspicious validity anti-pattern https://quinedot.github.io/rust-learning/pf-borrow-forever.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Area: New lints
Projects
None yet
Development

No branches or pull requests

2 participants