std-method

Integer checked_div and checked_rem

Calculate quotient and remainder safely. Zero divisors fail; signed MIN divided by -1 also fails for both methods. Expected stdout (not executed): Some(3) Some(2) None None Common mistake: Checking only for zero when using signed division.

Formal Syntax & Structure

rust syntaxrust
x.checked_div(y); x.checked_rem(y)

Working Example

Example Snippetrust
fn main() {    println!("{:?} {:?}", 17i32.checked_div(5), 17i32.checked_rem(5));    println!("{:?} {:?}", 17i32.checked_div(0), i32::MIN.checked_rem(-1));}
Rust Reference