Skip to content

field_reassign_with_default on struct with #[non_exhaustive] or private fields is false positive #6559

@bryanburgers

Description

@bryanburgers

Lint name: field_reassign_with_default

Given a library that contains a struct with a #[non_exhaustive] attribute on it:

#[derive(Default)]
#[non_exhaustive]
pub struct TestStruct {
    pub one: usize,
    pub two: usize,
}

Code like this causes a clippy warning:

fn main() {
    let mut t = the_lib::TestStruct::default();
    t.one = 1;
    t.two = 2;
    println!("{} {}", t.one, t.two);
}

Clippy would prefer to see the following code, which is a compiler error.

fn main() {
    let t = the_lib::TestStruct {
        one: 1,
        two: 2,
        ..the_lib::TestStruct::default()
    };
    println!("{} {}", t.one, t.two);
}
cannot create non-exhaustive struct using struct expression

Note that due to the rules of #[non_exhaustive] application, this is only an error when the struct is defined in a different crate (which is why I'm not able to provide a playground link).

The attribute #[non_exhaustive], when attached to a struct or the variant of an enum, will prevent code outside of the crate defining it from constructing said struct or variant.

Rust 1.40.0 release notes

Meta

  • cargo clippy -V: clippy 0.0.212 (e1884a8e 2020-12-29)
  • rustc -Vv:
    rustc 1.49.0 (e1884a8e3 2020-12-29)
    binary: rustc
    commit-hash: e1884a8e3c3e813aada8254edfa120e85bf5ffca
    commit-date: 2020-12-29
    host: x86_64-apple-darwin
    release: 1.49.0
    

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 have

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions