Module 3 • Lesson 13

Primitive Types Deep Dive

📚 8 min read 💻 Free Course 🦀 nixus.pro

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

  1. Implement simple bit flags: const ADMIN: u8 = 0b001, READ: u8 = 0b010, WRITE: u8 = 0b100. Write has_flag, set_flag, clear_flag functions
  2. Count uppercase, lowercase, digits, and other chars in a string using char methods
  3. Use checked arithmetic to safely multiply two user-provided numbers

🎉 Key Takeaways