rust-lang / rust-clippy

A bunch of lints to catch common mistakes and improve your Rust code. Book: https://doc.rust-lang.org/clippy/
https://rust-lang.github.io/rust-clippy/
Other
11.39k stars 1.54k forks source link

Suggestion: Make `needless_lifetimes` ignore functions that are, or contain, `unsafe`. #9694

Open TimNN opened 2 years ago

TimNN commented 2 years ago

Description

I've found myself somewhat frequently disabling the needless_lifetimes lint for functions that are, or contain, unsafe, primarily because I felt like it was better to be explicit in those case. (One example: more limited wrappers around pointer casts / transmutes).

IMO, given that unsafe can be used to circumvent the borrow checker, eliding the lifetimes increases complexity, since it's one more thing that authors and reviewers have to pay attention to (because they can't rely on the compiler to catch incorrect lifetimes / elision).

I don't know if such an exception would be too broad, but I believe that if a function is, or contains, unsafe, there's a high likelihood of explicit lifetimes being intentional.

And, maybe more importantly, getting the elision wrong can have more serious consequences, see e.g. https://github.com/rust-lang/rust-clippy/issues/9360.

(Nothing prevents authors from eliding the lifetimes on their own (i.e. I'm not advocating for an "use explicit lifetimes with unsafe" lint), but I don't think Clippy should suggest removing explicit lifetimes from these functions if they are present).

Version

No response

Additional Labels

No response

kraktus commented 2 years ago

Could be implemented as a lint configuration setting

lengyijun commented 1 year ago

I think lint should ignore the generic parameter, for example,

1078 -     pub fn iter<'a>(&'a self) -> Iter<'a, K, V> {
1078 +     pub fn iter(&self) -> Iter<'_, K, V> {

The explicit lifetime is much easier to read