pub trait SafeSub: Copy + Sub<Output = Self> {
// Required method
fn safe_sub(self, rhs: Self) -> Result<Self, SafeMathError>;
}Expand description
Safe subtraction operation with underflow checking.
This trait provides checked subtraction that returns a Result instead of panicking
or wrapping on underflow.
§Arguments
rhs- Right-hand side operand.
§Returns
Ok(result)- The difference ofselfandrhsif no underflow occurredErr(SafeMathError::Overflow)- If the subtraction would underflow
§Examples
use safe_math::{SafeSub, SafeMathError};
let a: u8 = 5;
let b: u8 = 3;
// Safe subtraction that works
assert_eq!(a.safe_sub(b), Ok(2));
// Safe subtraction that detects underflow
let c: u8 = 10;
assert_eq!(a.safe_sub(c), Err(SafeMathError::Overflow));§See also
SafeMathOps- Combined trait for all safe arithmetic operationsSafeMathError- Error type returned on arithmetic failures
Required Methods§
Sourcefn safe_sub(self, rhs: Self) -> Result<Self, SafeMathError>
fn safe_sub(self, rhs: Self) -> Result<Self, SafeMathError>
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.