checked_div checked_rem checked_shl
Cover the divide, remainder, and shift corners that checked_add misses: checked_div rejects zero, checked_shl rejects shifts past the width.
Code
fn main() {
// checked_div:除以零返回 None,不会 panic
println!("7 / 2 = {:?}", 7i32.checked_div(2));
println!("7 / 0 = {:?}", 7i32.checked_div(0));
// checked_rem:取余同样防零;余数符号跟随被除数
println!("7 % 3 = {:?}", 7i32.checked_rem(3));
println!("-7 % 3 = {:?}", (-7i32).checked_rem(3));
println!("7 % 0 = {:?}", 7i32.checked_rem(0));
// i32::MIN / -1 是唯一溢出的除法:结果 +1 放不进 i32
println!("min / -1 = {:?}", i32::MIN.checked_div(-1));
// checked_shl / checked_shr:位移量 ≥ 位宽返回 None,不静默截断
println!("1 << 3 = {:?}", 1u8.checked_shl(3));
println!("1 << 8 = {:?}", 1u8.checked_shl(8));
println!("255 >> 4 = {:?}", 255u8.checked_shr(4));
println!("255 >> 8 = {:?}", 255u8.checked_shr(8));
}Inside the snippet
Structurally, expect the function main and nothing else.
Caveats
- Plain i32 primitive methods cover every case; nothing external is referenced.
Putting it to use
Entry signature: fn main()
The demo output is labeled (7 / 2 =, 7 / 0 =, 7 % 3 =); each label names the call that printed it.
Interactive Tools for This Topic
FAQ
- What does checked_div checked_rem checked_shl print when run?
- Invoke the file as-is — the `7 / 2 =`, `7 / 0 =`, `7 % 3 =` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.