Skip to content

Lint suggestion: duplicate_impl_blocks #14867

Open
@amab8901

Description

@amab8901

What it does

It suggests you to refactor the code so you don't have redundant impl <Struct> blocks, and so that you have all the methods in one place (for that scope).

I would prefer to have the lint to apply to only impl blocks that are in the same scope, rather than globally across the program (because I like to have different impl blocks of the same struct in different files so that the method defined in the impl block is closest to the place where it's used).

If the file is so large that one would consider multiple impl blocks just to keep each method closer to where it's used, then it's probably a sign that the file is too large and needs to be split into multiple smaller files rather than having multiple impl blocks in the same file for the same struct.

Advantage

  • reduce redundant occurrences of impl <Struct> to improve signal/noise ratio
  • keep all the functions in one place (among those impl blocks defined in the same scope), so you can more easily/quickly/confidently know that you have found all the methods defined in this scope (usually the main scope of the file) and that there are no more methods to search for elsewhere in that scope (usually the main scope of the file)

Drawbacks

idk what drawbacks there would be besides the trivial ones like "it would increase the amount of code in clippy and it would take time/energy to implement this lint"

Example

fn main() {
    let structy = Structy::default();

    dbg!(&structy.field1());
    dbg!(&structy.field2());
}

#[derive(Default)]
pub(crate) struct Structy {
    field1: String,
    field2: String,
}

impl Structy {
    pub(crate) fn field1(&self) -> &String {
        &self.field1
    }
}

impl Structy {
    pub(crate) fn field2(&self) -> &String {
        &self.field2
    }
}

Could be written as:

fn main() {
    let structy = Structy::default();

    dbg!(&structy.field1());
    dbg!(&structy.field2());
}

#[derive(Default)]
pub(crate) struct Structy {
    field1: String,
    field2: String,
}

impl Structy {
    pub(crate) fn field1(&self) -> &String {
        &self.field1
    }

    pub(crate) fn field2(&self) -> &String {
        &self.field2
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-enhancementCategory: Enhancement of lints, like adding more cases or adding help messagesgood first issueThese issues are a good way to get started with Clippy

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions