Types, Shadowing and Overflow: checked, wrapping and the Debug Panic
Learn Rust's integer, float, char and string types, tuples and arrays, shadowing, and the four ways to handle overflow, including the real panic message that a debug build gives.
In this lesson you will
- Use the basic types
- Use shadowing and tuples
- Handle overflow explicitly
- Read the real overflow panic
About 28 minutes
The counter that panicked
Ines counts the revolutions of a turbine in a u8, which holds 0 to 255, and the program stops with the message “attempt to add with overflow”. In C the value would silently wrap, and in Go as well. Rust makes you choose: a debug build panics on overflow, so that the bug is found, and in a release build the default is to wrap, so you should never rely on either and use the methods that say what you mean.
| Type | Meaning |
|---|---|
| i8 to i128, u8 to u128 | Signed and unsigned integers of fixed size |
| isize, usize | Pointer-sized; usize is used for indexes and lengths |
| f32, f64 | Floating point; f64 is the default |
| bool, char | char is a 4-byte Unicode scalar value |
| (i32, f64, char) | A tuple of mixed types |
| [i32; 5] | An array of exactly 5 elements |
| &str, String | Borrowed and owned UTF-8 text |
The four ways to add numbers that might overflow are checked_add, which returns an Option and is None on overflow, wrapping_add, which wraps modulo the size, saturating_add, which stops at the largest or smallest value, and overflowing_add, which returns the wrapped value and a flag. Shadowing means declaring a new variable with the same name, as in let x = x * 2, which can even change the type, and is different from mutation. Strings are UTF-8, so len gives bytes, and chars().count() gives characters.
fn main() {
let a: u8 = 250;
println!("checked_add(10): {:?}, checked_add(5): {:?}", a.checked_add(10), a.checked_add(5));
println!("wrapping_add(10): {}, saturating_add(10): {}, overflowing_add(10): {:?}", a.wrapping_add(10), a.saturating_add(10), a.overflowing_add(10));
println!("i32 range: {} to {}, u64 max: {}", i32::MIN, i32::MAX, u64::MAX);
let spaces = " ";
let spaces = spaces.len();
println!("shadowed from a string to a number: {}", spaces);
let t: (i32, f64, char) = (500, 6.4, 'W');
let (x, y, z) = t;
println!("tuple: {} {} {} | first field: {}", x, y, z, t.0);
let arr = [10, 20, 30, 40, 50];
println!("array of {} sums to {}", arr.len(), arr.iter().sum::<i32>());
let d = 0.1 + 0.2;
println!("0.1 + 0.2 = {} | equal to 0.3? {} | close enough? {}", d, d == 0.3, (d - 0.3f64).abs() < 1e-9);
println!("7 / 2 = {} | 7.0 / 2.0 = {} | -7 % 3 = {} | rem_euclid = {}", 7 / 2, 7.0 / 2.0, -7 % 3, (-7i32).rem_euclid(3));
let s = "Zoë";
println!("{:?} has {} bytes and {} chars", s, s.len(), s.chars().count());
let big = 300i32;
println!("300 as u8 wraps to {} and -1 as u8 is {}", big as u8, -1i32 as u8);
}
checked_add(10): None, checked_add(5): Some(255)
wrapping_add(10): 4, saturating_add(10): 255, overflowing_add(10): (4, true)
i32 range: -2147483648 to 2147483647, u64 max: 18446744073709551615
shadowed from a string to a number: 3
tuple: 500 6.4 W | first field: 500
array of 5 sums to 150
0.1 + 0.2 = 0.30000000000000004 | equal to 0.3? false | close enough? true
7 / 2 = 3 | 7.0 / 2.0 = 3.5 | -7 % 3 = -1 | rem_euclid = 2
"Zoë" has 4 bytes and 3 chars
300 as u8 wraps to 44 and -1 as u8 is 255
fn main() {
let start: u8 = std::env::args().count() as u8 + 249;
let total = start + 10;
println!("total {}", total);
}
thread 'main' (15983) panicked at m.rs:3:17:
attempt to add with overflow
stack backtrace:
0: __rustc::rust_begin_unwind
at /rustc/2d8144b7880597b6e6d3dfd63a9a9efae3f533d3/library/std/src/panicking.rs:689:5
1: core::panicking::panic_fmt
at /rustc/2d8144b7880597b6e6d3dfd63a9a9efae3f533d3/library/core/src/panicking.rs:80:14
2: core::panicking::panic_const::panic_const_add_overflow
at /rustc/2d8144b7880597b6e6d3dfd63a9a9efae3f533d3/library/core/src/panicking.rs:175:17
3: m::main
4: <fn() as core::ops::function::FnOnce<()>>::call_once
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
The four kinds of addition on the u8 value 250 show the choices. checked_add(10) gave None, because 260 does not fit, and checked_add(5) gave Some(255). wrapping_add(10) wrapped to 4, saturating_add(10) stopped at the maximum 255, and overflowing_add(10) returned the wrapped value together with a true flag, (4, true). Each says in the name exactly what it does, so a reader never has to guess. The ranges are -2,147,483,648 to 2,147,483,647 for i32 and 18,446,744,073,709,551,615 for the largest u64.
Shadowing turned the string of spaces into its length, 3, with a new let and the same name, which a mutable variable could not do because the type changes. The tuple was unpacked into three variables and its first field read with t.0, the array of 5 elements sums to 150, and floating point gave 0.1 + 0.2 = 0.30000000000000004, not equal to 0.3 (false) but close (true), the same as in every IEEE language. Integer division truncates, -7 % 3 is -1, and rem_euclid gives the never-negative remainder 2. The string “Zoë” is 4 bytes but 3 characters, since ë takes two bytes, and the casts with as wrap silently: 300 as u8 is 44, and -1 as u8 is 255, so prefer try_from for conversions that might lose data.
The second program adds 10 to a u8 that the program computes at run time as 250. In the debug build, the default of rustc, it stopped with the panic shown above, naming the line and the message “attempt to add with overflow”, which is how the bug is found during development. An optimised release build would wrap silently unless you enable overflow checks, so the explicit methods are the portable way to say what you want.
Check by hand: 250 + 10 = 260, and 260 mod 256 = 4. The saturating result is 255, the largest u8. -7 divided by 2 is -3.5 and truncates to -3, so 7 / 2 = 3, and -7 % 3 = -1 while the Euclidean remainder is 2, since -7 = 3 x (-3) + 2. And 300 mod 256 = 44.
Writing x as u8 silently drops the high bits. For conversions that may fail, use u8::try_from(x), which returns a Result that you must handle.
Use checked_ when overflow is an error you want to handle, wrapping_ for hash and counter arithmetic that is meant to wrap, saturating_ for clamping and overflowing_ when you need both the value and the flag.
Every program in this lesson was compiled with rustc 1.97 (edition 2021) and run while the course was written. Rust releases every six weeks and its compiler messages improve all the time, so check doc.rust-lang.org for the current edition and wording. The panic message was produced by a debug build, which is the default for rustc and cargo build.
Practice
Try the four methods with i8 and the value 127, and with multiplication. Write a function that converts an i64 to u8 with try_from and prints the error for 300. Shadow a variable three times, changing its type each time, and print it.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What does checked_add return on overflow?
- A panic
- The wrapped value
- None
- Zero
It returns an Option.
What does shadowing allow?
- Changing a constant
- A new variable with the same name, even of a different type
- Hiding a function
- Deleting a variable
It is not mutation.
What does a debug build do on integer overflow?
- Wraps silently
- Panics
- Saturates
- Ignores it
To find the bug early.
How long is the string “Zoë” in bytes?
- 4
- 3
- 2
- 5
ë takes two bytes in UTF-8.
Why prefer try_from to as?
- as silently drops bits
- as is slower
- try_from is a macro
- as is unsafe
try_from returns a Result.
Summary
- Rust has fixed-size integer types, f64 floats, tuples and arrays.
- Overflow is explicit: checked, wrapping, saturating or overflowing methods.
- A debug build panics on overflow.
- Shadowing creates a new variable; as casts wrap silently.
Questions
What is usize for?
It is the integer type that holds sizes and indexes, as wide as a pointer, so 64 bits on a 64-bit system.
Is there a decimal type?
Not in the standard library. For money, store whole cents in an integer, or use a crate such as rust_decimal after checking its documentation.
What is a char in Rust?
A Unicode scalar value, four bytes wide, written in single quotes. A string is not an array of chars, but a sequence of UTF-8 bytes.
