Commit c705c93
committed
Implement
If a type has an auto-derived `Default` trait and a `fn new() -> Self`,
this lint checks if the `new()` method performs custom logic rather
than simply calling the `default()` method.
Users expect the `new()` method to be equivalent to `default()`,
so if the `Default` trait is auto-derived, the `new()` method should
not perform custom logic. Otherwise, there is a risk of different
behavior between the two instantiation methods.
```rust
struct MyStruct(i32);
impl MyStruct {
fn new() -> Self {
Self(42)
}
}
```
Users are unlikely to notice that `MyStruct::new()` and `MyStruct::default()` would produce
different results. The `new()` method should use auto-derived `default()` instead to be consistent:
```rust
struct MyStruct(i32);
impl MyStruct {
fn new() -> Self {
Self::default()
}
}
```
Alternatively, if the `new()` method requires a non-default initialization, implement a custom `Default`.
This also allows you to mark the `new()` implementation as `const`:
```rust
struct MyStruct(i32);
impl MyStruct {
const fn new() -> Self {
Self(42)
}
}
impl Default for MyStruct {
fn default() -> Self {
Self::new()
}
}
```default_mismatches_new lint1 parent 0acc59a commit c705c93
13 files changed
Lines changed: 863 additions & 236 deletions
File tree
- clippy_lints/src
- tests/ui
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
6633 | 6633 | | |
6634 | 6634 | | |
6635 | 6635 | | |
| 6636 | + | |
6636 | 6637 | | |
6637 | 6638 | | |
6638 | 6639 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
564 | 564 | | |
565 | 565 | | |
566 | 566 | | |
567 | | - | |
| 567 | + | |
| 568 | + | |
568 | 569 | | |
569 | 570 | | |
570 | 571 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
265 | 265 | | |
266 | 266 | | |
267 | 267 | | |
268 | | - | |
| 268 | + | |
269 | 269 | | |
270 | 270 | | |
271 | 271 | | |
| |||
615 | 615 | | |
616 | 616 | | |
617 | 617 | | |
618 | | - | |
| 618 | + | |
619 | 619 | | |
620 | 620 | | |
621 | 621 | | |
| |||
0 commit comments