Numeric Types and Safe Arithmetic
fn main() {
// Integer types: i8 i16 i32 i64 i128 isize / u8 u16 u32 u64 u128 usize
let x: i32 = 1_000_000; // underscores for readability
let y: u64 = 0xFF_AA_BB; // hex
let z: u8 = 0b1111_0000; // binary
// Checked arithmetic
let result = i32::MAX.checked_add(1);
println!("{:?}", result); // None - would overflow
let ok = 100i32.checked_add(50);
println!("{:?}", ok); // Some(150)
// Saturating: clamps to max/min
println!("{}", i32::MAX.saturating_add(1)); // 2147483647
// Wrapping: wraps around (C behavior)
println!("{}", i32::MAX.wrapping_add(1)); // -2147483648
// Powers, abs, min, max
println!("{}", 2i32.pow(10)); // 1024
println!("{}", (-5i32).abs()); // 5
println!("{}", 3i32.max(7)); // 7
println!("{}", 3.0f64.sqrt()); // ~1.732
println!("{}", f64::NAN.is_nan()); // true
}Boolean, Char, Type Aliases
fn main() {
// Rust requires explicit bool - no truthy/falsy
let b: bool = true;
// if 1 {} // ERROR
if b && !false { println!("both true"); }
// Bitwise ops
let flags: u8 = 0b1100;
println!("{:08b}", flags | 0b0011); // OR: 00001111
println!("{:08b}", flags & 0b1010); // AND: 00001000
// char is 4 bytes - full Unicode
let c = 'Z';
println!("{}", c.is_uppercase()); // true
println!("{}", c.to_lowercase().next().unwrap()); // z
println!("{}", 'A' as u8); // 65
// Iterate string as chars (not bytes!)
let s = "Hello, 世界";
println!("chars: {}", s.chars().count()); // 9, not 9 bytes
// Type alias
type UserId = u64;
type Score = f32;
let id: UserId = 12345;
let score: Score = 98.5;
println!("{} -> {}", id, score);
}🎯 Practice
- Implement simple bit flags: const ADMIN: u8 = 0b001, READ: u8 = 0b010, WRITE: u8 = 0b100. Write has_flag, set_flag, clear_flag functions
- Count uppercase, lowercase, digits, and other chars in a string using char methods
- Use checked arithmetic to safely multiply two user-provided numbers
🎉 Key Takeaways
- Use checked_/saturating_/wrapping_ for explicit overflow behavior
- char is 4 bytes - full Unicode scalar value, not ASCII
- Use .chars() to iterate strings; .len() gives byte count
- Type aliases improve readability without creating new types