Integer Overflow and Methods
In debug builds arithmetic overflow panics, and in release it wraps. Methods such as checked_add, wrapping_add and saturating_add make the behaviour explicit.
Example
let x: u8 = 250;
println!("{:?}", x.checked_add(10));
println!("{}", x.wrapping_add(10));
println!("{}", x.saturating_add(10));
println!("{}", u8::MAX);Result
None 4 255 255
Exercise
Return None on overflow.
x.(10)
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.