Primitive Types Exercises

Overview

These exercises cover Rust’s basic built-in types: booleans, characters, arrays, slices, and tuples.


primitive_types1 - Booleans

Concept: The bool type

fn main() {
    let is_morning = true;
    if is_morning {
        println!("Good morning!");
    }
 
    let is_evening = !is_morning;  // Negation with !
    if is_evening {
        println!("Good evening!");
    }
}

Key Takeaway: Booleans are true or false. Negate with !.


primitive_types2 - Characters

Concept: The char type (Unicode scalar values)

fn main() {
    let my_first_initial = 'C';
    if my_first_initial.is_alphabetic() {
        println!("Alphabetical!");
    }
 
    let your_character = '🦀';  // Emojis work!
    // ...
}

Key Takeaways:

  • char uses single quotes (strings use double quotes)
  • char is 4 bytes — it’s a Unicode scalar value, not just ASCII
  • Methods like .is_alphabetic() and .is_numeric() are available

primitive_types3 - Arrays

Concept: Fixed-size collections

fn main() {
    // [value; count] syntax creates an array with repeated values
    let a = [42; 100];  // 100 elements, all 42
 
    if a.len() >= 100 {
        println!("Wow, that's a big array!");
    }
}

Key Takeaways:

  • Arrays have a fixed size known at compile time
  • Type annotation: [T; N] where T is the type and N is the length
  • Initialize with [value; count] for repeated values

primitive_types4 - Slices

Concept: References to contiguous sequences

#[test]
fn slice_out_of_array() {
    let a = [1, 2, 3, 4, 5];
    //       0  1  2  3  4  <- indices
 
    // Exclusive upper bound (1..4 = elements 1, 2, 3)
    let nice_slice = &a[1..4];
    assert_eq!([2, 3, 4], nice_slice);
 
    // Inclusive upper bound (1..=3 = elements 1, 2, 3)
    let nice_slice = &a[1..=3];
    assert_eq!([2, 3, 4], nice_slice);
}

Key Takeaways:

  • Slices are references to a portion of an array
  • start..end — end is exclusive
  • start..=end — end is inclusive
  • Slices don’t own data — they borrow it

primitive_types5 - Tuple Destructuring

Concept: Extracting values from tuples

fn main() {
    let cat = ("Furry McFurson", 3.5);
 
    // Destructuring
    let (name, age) = cat;
 
    println!("{name} is {age} years old");
}

Key Takeaway: Destructuring extracts multiple values at once — elegant and readable.


primitive_types6 - Tuple Indexing

Concept: Accessing tuple elements by index

#[test]
fn indexing_tuple() {
    let numbers = (1, 2, 3);
 
    // Tuple indexing uses .0, .1, .2, etc.
    let second = numbers.1;
 
    assert_eq!(second, 2);
}

Key Takeaways:

  • Access tuple elements with .0, .1, .2, etc.
  • Unlike arrays, tuples use dot notation (not bracket indexing)
  • Tuples can have mixed types: (i32, &str, f64)

Rust Book Reference