Skip to content

new_without_default does not include generic bounds in suggestions #11267

@abcalphabet

Description

@abcalphabet

Summary

new_without_default suggests the implementation of the Default trait on generics without the specified trait bounds. This leads to the suggested change not compiling.

Playground example

Reproducer

I tried this code:

use std::collections::HashMap;
use std::hash::Hash;

pub struct MyStruct<K, V>
where
    K: Hash + Eq + PartialEq 
{
    _map: HashMap<K, V>,
}

impl<K, V> MyStruct<K, V>
where
    K: Hash + Eq + PartialEq 
{
    pub fn new() -> Self {
        Self {
            _map: HashMap::new(),
        }
    }
}

I expected to see this happen:

Either no warning, or

warning: you should consider adding a `Default` implementation for `MyStruct<K, V>`
  --> src/lib.rs:15:5
   |
15 | /     pub fn new() -> Self {
16 | |         Self {
17 | |             _map: HashMap::new(),
18 | |         }
19 | |     }
   | |_____^
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#new_without_default
   = note: `#[warn(clippy::new_without_default)]` on by default
help: try adding this
   |
11 + impl<K, V> Default for MyStruct<K, V>
12 + where
13 +     K: Hash + Eq + PartialEq  {
14 +     fn default() -> Self {
15 +         Self::new()
16 +     }
17 + }

Instead, this happened:

warning: you should consider adding a `Default` implementation for `MyStruct<K, V>`
  --> src/lib.rs:15:5
   |
15 | /     pub fn new() -> Self {
16 | |         Self {
17 | |             _map: HashMap::new(),
18 | |         }
19 | |     }
   | |_____^
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#new_without_default
   = note: `#[warn(clippy::new_without_default)]` on by default
help: try adding this
   |
11 + impl<K, V> Default for MyStruct<K, V> {
12 +     fn default() -> Self {
13 +         Self::new()
14 +     }
15 + }

Version

rustc 1.71.0 (8ede3aae2 2023-07-12)
binary: rustc
commit-hash: 8ede3aae28fe6e4d52b38157d7bfe0d3bceef225
commit-date: 2023-07-12
host: aarch64-apple-darwin
release: 1.71.0
LLVM version: 16.0.5

Additional Labels

No response

Metadata

Metadata

Assignees

Labels

C-bugCategory: Clippy is not doing the correct thing

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions