Give values the right shape.
Choose numeric types and handle arithmetic boundaries deliberately.
01 Understand the contract
Rust distinguishes signed integers such as i32, unsigned integers such as u64, and platform-sized usize values used for indexing. Floating-point values use f32 or f64 and cannot represent every decimal fraction exactly. A bool is true or false. A char is one Unicode scalar value, which can occupy more than one UTF-8 byte and is not necessarily an entire visible grapheme. Integer overflow behavior depends on build settings; checked arithmetic makes the boundary explicit in every build.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
fn main() {
let temperature: i32 = -4;
let ready: bool = temperature < 0;
let symbol: char = '🦀';
let safe = u8::MAX.checked_add(1);
println!("{temperature} {ready} {symbol}");
println!("overflow: {safe:?}");
}-4 true 🦀 overflow: None
- 1
The signed integer can represent negative temperatures.
- 2
checked_add returns None when the result would exceed u8.
- 3
Debug formatting prints the Option variant.
cargo run -p lesson_scalar_types03 Mind the boundary
04 Your next build
Use u8::try_from to reject 300, and checked_mul to detect overflow in 200_u8 * 2.
Reveal one possible solution +
fn main() {
assert!(u8::try_from(300).is_err());
assert_eq!(200_u8.checked_mul(2), None);
assert_eq!(12_u8.checked_mul(2), Some(24));
}05 Check your reasoning
Which type normally indexes a slice?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.