Skip to content

False positive in redundant_closure when closure value's lifetime is constrained #4002

Closed
@dtolnay

Description

@dtolnay
pub struct Arg;

pub trait Trait {
    fn f(_: Arg);
}

fn take<T: 'static>(_: T) {}

pub fn f<G: Trait>() {
    take(|v| G::f(v));
}

Clippy recommends take(G::f):

warning: redundant closure found
  --> src/main.rs:10:10
   |
10 |     take(|v| G::f(v));
   |          ^^^^^^^^^^^ help: remove closure as shown: `G::f`
   |
   = note: #[warn(clippy::redundant_closure)] on by default
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#redundant_closure

The original code compiles, while the code suggested by Clippy does not:

error[E0310]: the parameter type `G` may not live long enough
  --> src/main.rs:10:5
   |
9  | pub fn f<G: Trait>() {
   |          -- help: consider adding an explicit lifetime bound `G: 'static`...
10 |     take(G::f);
   |     ^^^^
   |
note: ...so that the type `fn(Arg) {<G as Trait>::f}` will meet its required lifetime bounds
  --> src/main.rs:10:5
   |
10 |     take(G::f);
   |     ^^^^

I believe the difference is that |v| G::f(v) is an ordinary 'static closure (Arg) -> () that captures nothing and G does not appear in its type, while G::f is according to the compiler a fn(Arg) {<G as Trait>::f} in which G does appear. Due to G appearing in its official type, the closure cannot be considered 'static unless G is 'static.

Mentioning @dgreid who encountered this in Chrome OS.


clippy 0.0.212 (fbb3a47 2019-04-14)

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't haveI-suggestion-causes-errorIssue: The suggestions provided by this Lint cause an ICE/error when appliedL-suggestionLint: Improving, adding or fixing lint suggestions

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions