Rust Operators and Checked Arithmetic
Reject overflow instead of depending on build settings.
How it works
Arithmetic operators work on typed values, and integer division truncates according to the integer rules rather than producing a fraction. Overflow behaviour depends on the operation and configured checks. For user-supplied quantities, checked arithmetic returns Option so the caller must handle the out-of-range case. This is a numerical boundary decision, separate from ownership safety.
Run the code
Reviewed with Rust 1.97.0, edition 2024, using the standard library only. Save the complete download as lesson-name.rs in a separate learning folder, compile with rustc --edition=2024 lesson-name.rs and run the resulting program (lesson-name.exe on Windows). Use the actual lesson filename. The final project includes complete Cargo package files; run cargo test --offline and cargo run --offline from that separate package folder. There is no Rust browser runner; PHP, Apache and MySQL are not needed.
This complete example was executed in the stated local review environment.
Example
fn main() {
assert_eq!(7_u32 / 3, 2);
assert_eq!(255_u8.checked_add(1), None);
assert_eq!(6_u32.checked_mul(3), Some(18));
println!("Integer division is 2; overflow refused; product is 18");
}
Expected result
Integer division is 2; overflow refused; product is 18
The examples compare three distinct contracts: integer division, an overflowing addition and a valid multiplication. Use a larger type only if its range actually covers the domain; it does not remove the need to validate external quantities. A floating-point amount also has rounding and finite-value concerns.
Primary technical reference: Rust documentation.