Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Detect structs with manual new and automatic derive #14075

Open
nyurik opened this issue Jan 25, 2025 · 0 comments
Open

Detect structs with manual new and automatic derive #14075

nyurik opened this issue Jan 25, 2025 · 0 comments
Labels
A-lint Area: New lints

Comments

@nyurik
Copy link
Contributor

nyurik commented Jan 25, 2025

What it does

As this bug in rust compiler shows, it is easy to implement a non-trivial new() method, while using #[derive(Default)] -- thus having two different ways to instantiate a struct, most likely creating bugs. I suspect there is a almost no good use case for the fn new() -> Self (without parameters) to contain anything other than { Self::default() }.

Other considerations

Advantage

  • keeps Default and new consistent
  • prevents bugs due to accidental multiple implementations

Drawbacks

There might be some strange usecase for new to be different from default. I couldn't come up with one, but I am sure something could exist...

Example

#[derive(Default)]
struct MyStruct(u32);

impl MyStruct {
  fn new() -> Self { Self(42) }
}

Could be written as:

impl MyStruct {
  fn new() -> Self { Self::default() }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Area: New lints
Projects
None yet
Development

No branches or pull requests

1 participant