rust-lang / rust-lang/rust-clippy

Detect structs with manual `new` and automatic `derive`

Open
#14,075 2 comments 0 reactions 1 assignee View on GitHub

@nyurik is already working on this.

Since Feb 17, 2025.

A-lint
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

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
  • We may want to warn if there is a fn new() that returns anything other than Self, like Result or Option or some other type.
  • This proposal is the reverse of #12662 idea
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() }
}

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.