rust-lang / rust-lang/rust-clippy
Implement `std::iter::Sum` if `std::ops::Add` is implemented
Nobody has claimed this yet.
- 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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