Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ EXPRESS THE WORK
BUILD NOTE 08 / 53

Small collections, clear contracts.

Model fixed shapes with tuples and fixed lengths with arrays.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

01 Understand the contract

A tuple groups a fixed number of potentially different types. An array holds a fixed number of elements of one type, and its length is part of its type. Destructuring names the useful parts of either shape. Direct indexing panics when an index is out of bounds; get returns an Option so absence can be handled. If size needs to grow dynamically, use a Vec instead. Use a struct rather than a long tuple when field names carry important meaning.

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.

lessons/tuples-arrays/src/main.rs
fn main() {
    let location = ("Cape Town", -33.9_f64);
    let (city, latitude) = location;
    let samples = [4, 8, 12];
    println!("{city}: {latitude}");
    println!("last={:?}, missing={:?}", samples.get(2), samples.get(9));
}
↳ EXPECTED OUTPUT
Cape Town: -33.9
last=Some(12), missing=None
  1. 1

    The tuple stores a string slice and a float.

  2. 2

    Destructuring introduces readable names.

  3. 3

    get avoids a panic for an unknown index.

From the extracted rust-workbench folder
cargo run -p lesson_tuples_arrays

03 Mind the boundary

04 Your next build

A SMALL MISSION

Destructure an RGB tuple and calculate the sum of the channels.

Reveal one possible solution +
solutions/tuples-arrays/src/main.rs
fn main() {
    let (red, green, blue) = (20_u16, 30_u16, 40_u16);
    assert_eq!(red + green + blue, 90);
    let empty: [i32; 0] = [];
    assert_eq!(empty.get(0), None);
}

05 Check your reasoning

QUICK SIGNAL CHECK

What does an out-of-range array.get(index) return?

ONE MORE CONTRACT YOU CAN EXPLAIN.

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.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.