Skip to content

field_reassign_with_default false positive with closure capturing variable that was initialized to default #10136

@Johan-Mi

Description

@Johan-Mi

Summary

The field_reassign_with_default lint performs a check to make sure that the the reassignment does not involve the variable that was initialized with default(), but this check fails if the variable is captured by a closure.

Lint Name

field_reassign_with_default

Reproducer

I tried this code:

struct Collection {
    items: Vec<i32>,
    len: usize,
}

impl Default for Collection {
    fn default() -> Self {
        Self {
            items: vec![1, 2, 3],
            len: 0,
        }
    }
}

fn main() {
    let mut c = Collection::default();
    c.len = (|| c.items.len())();
}

I saw this happen:

warning: field assignment outside of initializer for an instance created with Default::default()
  --> src/main.rs:17:5
   |
17 |     c.len = (|| c.items.len())();
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
note: consider initializing the variable with `Collection { len: (|| c.items.len())(), ..Default::default() }` and removing relevant reassignments
  --> src/main.rs:16:5
   |
16 |     let mut c = Collection::default();
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#field_reassign_with_default
   = note: `#[warn(clippy::field_reassign_with_default)]` on by default

I expected to see this happen:

The lint should not trigger since the expression that c.len is being reassigned to involves c, making the suggestion invalid.

Version

rustc 1.66.0 (69f9c33d7 2022-12-12)
binary: rustc
commit-hash: 69f9c33d71c871fc16ac445211281c6e7a340943
commit-date: 2022-12-12
host: x86_64-unknown-linux-gnu
release: 1.66.0
LLVM version: 15.0.2

Additional Labels

@rustbot label +I-suggestion-causes-error

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 applied

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions