Skip to content

Commit

Permalink
Sum implements AddAssign
Browse files Browse the repository at this point in the history
  • Loading branch information
devjgm committed Dec 16, 2023
1 parent 4d10221 commit d34253e
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
13 changes: 12 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::fmt;
use std::ops::Add;
use std::ops::{Add, AddAssign};

/// This enum represents the sum of a sequence of numbers that may be integers or floating point.
/// Integer is the default. When a floating point number is added to the sum, the type is converted
Expand All @@ -24,6 +24,13 @@ impl Add for Sum {
}
}

impl AddAssign for Sum {
/// Adds two Sums. If either is a Float, the result will be a Float.
fn add_assign(&mut self, other: Self) {
*self = *self + other;
}
}

impl fmt::Display for Sum {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Expand Down Expand Up @@ -51,6 +58,10 @@ mod tests {
let a = Sum::Integer(1);
let b = Sum::Integer(2);
assert_eq!(a + b, Sum::Integer(3));

let mut c = a;
c += b;
assert_eq!(c, Sum::Integer(3));
}

#[test]
Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
}
}
};
sum = sum + n;
sum += n;
log::debug!("{i}: col={col:?}, n={n:?}, sum={sum:?}");
}
}
Expand Down

0 comments on commit d34253e

Please sign in to comment.