rust-lang / rust-lang/rust-clippy

Implement `std::iter::Sum` if `std::ops::Add` is implemented

Open
#10,320 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

What it does

If you have a type that implement std::ops::Add it should probably also implement std::iter::Sum to allow summing up an iterator of such values

Lint Name

add_without_sum

Category

No response

Advantage

Removed the need to do something like iter.fold(T::zero(), |acc, x| acc + x);

Drawbacks

No response

Example
struct Point {
    x: i32,
    y: i32,
}

impl Add for Point {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        Self {
            x: self.x + other.x,
            y: self.y + other.y,
        }
    }
}

Could be written as:

struct Point {
    x: i32,
    y: i32,
}

impl Add for Point {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        Self {
            x: self.x + other.x,
            y: self.y + other.y,
        }
    }
}

impl Sum for Point {
    fn sum<I: Iterator<Item=Self>>(iter: I) -> Self {
        iter.fold(Point{x:0,y:0}, |acc, x| acc + x)
    }
}

// Alternativly:
impl Sum for Point {
    fn sum<I: Iterator<Item=Self>>(mut iter: I) -> Self {
        let first = iter.next().unwrap_or(Point{x:0,y:0});
        iter.fold(first, |acc, x| acc + x)
    }
}

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.

Research direction

Start with the issue's std::ops::Add and std::iter::Sum examples, then review existing Clippy lint patterns for trait-implementation suggestions. Clarify the proposed lint's applicability, diagnostics, and handling of empty sums; done means the agreed behavior is implemented and covered by Clippy tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.