Reputation: 97008
Is it possible to disable Rust's lifetime elision on a per-file basis, maybe with an #[attribute]
?
I'm learning about lifetimes and I think this might help.
Upvotes: 8
Views: 819
Reputation: 431759
Is it possible to disable Rust's lifetime elision on a per-file basis
No.
The best alternative I can offer is to request a Clippy feature that is the opposite of needless_lifetimes
and then enable it. I don't know if such a request would be wanted by other people though.
In the meantime, you could enable that lint and manually make sure that it fires for every function.
For reference, there are only 3 rules:
Lifetimes on function or method parameters are called input lifetimes, and lifetimes on return values are called output lifetimes.
The compiler uses three rules to figure out what lifetimes references have when there aren’t explicit annotations. The first rule applies to input lifetimes, and the second and third rules apply to output lifetimes. If the compiler gets to the end of the three rules and there are still references for which it can’t figure out lifetimes, the compiler will stop with an error. These rules apply to
fn
definitions as well asimpl
blocks.The first rule is that each parameter that is a reference gets its own lifetime parameter. In other words, a function with one parameter gets one lifetime parameter:
fn foo<'a>(x: &'a i32)
; a function with two parameters gets two separate lifetime parameters:fn foo<'a, 'b>(x: &'a i32, y: &'b i32)
; and so on.The second rule is if there is exactly one input lifetime parameter, that lifetime is assigned to all output lifetime parameters:
fn foo<'a>(x: &'a i32) -> &'a i32
.The third rule is if there are multiple input lifetime parameters, but one of them is
&self
or&mut self
because this is a method, the lifetime ofself
is assigned to all output lifetime parameters. This third rule makes methods much nicer to read and write because fewer symbols are necessary.
For what it's worth, before Rust 1.0, these 3 lifetime elision rules didn't exist, there was only the first. However, something like 87% of all functions and methods in the standard library that used references were covered by the 3 elision rules, which is why they were adopted. Lifetime elision is the common case.
Upvotes: 8