pub trait SafeDiv: Copy + Div<Output = Self> {
// Required method
fn safe_div(self, rhs: Self) -> Result<Self, SafeMathError>;
}Expand description
Safe division operation with division-by-zero checking.
This trait provides checked division that returns a Result instead of panicking
when attempting to divide by zero. It also handles potential overflow cases
for signed integer division.
§Arguments
rhs- Right-hand side operand (divisor).
§Returns
Ok(result)- The quotient ofselfdivided byrhsif division is validErr(SafeMathError::DivisionByZero)- Ifrhsis zeroErr(SafeMathError::Overflow)- If the division would overflow (e.g., MIN/-1 for signed integers)
§Examples
use safe_math::{SafeDiv, SafeMathError};
let a: u8 = 10;
let b: u8 = 2;
// Safe division that works
assert_eq!(a.safe_div(b), Ok(5));
// Safe division that detects division by zero
let zero: u8 = 0;
assert_eq!(a.safe_div(zero), Err(SafeMathError::DivisionByZero));
§See also
SafeMathOps- Combined trait for all safe arithmetic operationsSafeMathError- Error type returned on arithmetic failuresSafeRem- Safe remainder operations
Required Methods§
Sourcefn safe_div(self, rhs: Self) -> Result<Self, SafeMathError>
fn safe_div(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.