Small collections, clear contracts.
Model fixed shapes with tuples and fixed lengths with arrays.
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.
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));
}Cape Town: -33.9 last=Some(12), missing=None
- 1
The tuple stores a string slice and a float.
- 2
Destructuring introduces readable names.
- 3
get avoids a panic for an unknown index.
cargo run -p lesson_tuples_arrays03 Mind the boundary
04 Your next build
Destructure an RGB tuple and calculate the sum of the channels.
Reveal one possible solution +
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
What does an out-of-range array.get(index) return?
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.