pub trait SafeAdd: Copy + Add<Output = Self> {
// Required method
fn safe_add(self, rhs: Self) -> Result<Self, SafeMathError>;
}Expand description
Safe addition operation with overflow checking.
This trait provides checked addition that returns a Result instead of panicking
or wrapping on overflow.
§Arguments
rhs- Right-hand side operand.
§Returns
Ok(result)- The sum ofselfandrhsif no overflow occurredErr(SafeMathError::Overflow)- If the addition would overflow
§Examples
use safe_math::{SafeAdd, SafeMathError};
let a: u8 = 250;
let b: u8 = 5;
// Safe addition that works
assert_eq!(a.safe_add(b), Ok(255));
// Safe addition that detects overflow
let c: u8 = 251;
assert_eq!(a.safe_add(c), Err(SafeMathError::Overflow));§See also
SafeMathOps- Combined trait for all safe arithmetic operationsSafeMathError- Error type returned on arithmetic failures
Required Methods§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.