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.5k stars 1.55k forks source link

Exception to `struct_field_names` #12922

Open emilyyyylime opened 5 months ago

emilyyyylime commented 5 months ago

Summary

I propose that the clippy::struct_field_names lint, which checks for struct fields whose names share words with the struct's name, check the type name of the struct field—and forego emitting the lint if the field name matches its type (especially from a different scope).

Lint Name

struct_field_names

Reproducer

Some motivating examples:

pub struct App {
    app: widgetui::App, // field name starts with the struct's name
    // ...
}
pub struct Client {
    http_client: reqwest::Client, // field name ends with the struct's name
    // ...
}

Version

rustc 1.76.0 (07dca489a 2024-02-04)
binary: rustc
commit-hash: 07dca489ac2d933c78d3c5158e3f43beefeb02ce
commit-date: 2024-02-04
host: x86_64-unknown-linux-gnu
release: 1.76.0
LLVM version: 17.0.6

Additional Labels

No response

emilyyyylime commented 5 months ago

also related

struct Foo {
    foo_type: FooType,
}

renaming to type would not be possible as it's a reserved identifier

alexkazik commented 5 months ago

I think this should be also no error since the field name is identical to the type name (except snake vs. pascal case)

struct Foo {
    foo_client: FooClient,
}
duelafn commented 4 months ago

Regardless of whether the name matches the type, if there is only a single field with a match, I don't think this lint should trigger. Example,

struct Foo {
    foo: String,
    bar: i64,
    ... more or not
}

Yes, "foo" could be replaced by "inner" or some such, but perhaps that should be a different lint. The example in the clippy explainer suggests that this is (and I interporeted it as) primarily about unnecessary repetition as in the example struct Cake { cake_sugar: u8, cake_flour: u8, cake_eggs: u8 }.

Thanks!

rustc 1.78.0 (9b00956e5 2024-04-29)