C.W.K.
Stream
Lesson 02 of 05 · published

Tuples & Arrays

~10 min · types, tuples, arrays

Level 0Rust Curious
0 XP0/80 lessons0/19 achievements
0/100 XP to next level100 XP to go0% complete

Two built-in ways to group values: the tuple (mixed types, fixed count) and the array (one type, fixed count). Both live on the stack, both have a size known at compile time.

Tuples

A tuple bundles a fixed number of values of possibly different types: (i32, f64, char). You destructure it with a let pattern, or reach a field by position with .0, .1. Tuples shine for returning multiple values from a function without inventing a struct for a one-off.

Arrays

An array is a fixed-length run of one type: [i32; 4] is exactly four i32s, stack-allocated, length baked into the type. Indexing is bounds-checked — go past the end and Rust panics rather than reading stray memory (the C buffer-overrun, eliminated). For a sequence that grows, you want a Vec, which the Collections track covers.

Array vs Vec: stack vs heap, fixed vs growable. An array [T; N] has a compile-time length and lives on the stack. A Vec grows at runtime and lives on the heap. Use an array when the size is truly fixed and known; reach for Vec the moment it needs to grow.

Destructuring is everywhere

Pattern-destructuring a tuple in a let is your first taste of Rust's pattern matching, which runs through the whole language. let (x, y) = point; pulls both values out at once — you'll see this same shape in match, function parameters, and if let later.

Code

Tuple destructuring and a bounds-checked array·rust
fn main() {
    // Tuple: mixed types, accessed by position or destructured
    let person = ("Ferris", 3, true);
    let (name, age, _active) = person; // destructure
    println!("{name} is {age}, field 2 = {}", person.2);

    // Array: one type, fixed length, bounds-checked
    let scores = [90, 85, 100, 70];
    println!("first = {}, len = {}", scores[0], scores.len());
    // scores[10];  // panics: index out of bounds (no stray reads)
}

External links

Exercise

Write a function that takes a &[i32] and returns a tuple (i32, i32) of the min and max. Destructure the result at the call site into two named variables. Then deliberately index one past the array's end and observe the panic — note it's a clean panic, not a silent wrong read.
Hint
Returning (min, max) and destructuring with let (lo, hi) = ...; is the idiomatic quick multi-value. The out-of-bounds panic is Rust refusing to read memory it can't prove is valid.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue
💛 by Ttoriwarm

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.