Skip to main content

Tuples and arrays

A tuple groups a fixed number of values that can each have a different type. It is the tidy way to return two things from a function without inventing a struct for it.

An array `[T; N]` holds exactly N values of one type, and its length is part of the type. That means the compiler knows the size, the data lives on the stack, and out-of-range indexing is caught — at compile time when the index is a literal, and at runtime with a clear panic otherwise.

When you need to grow, you want a `Vec`. Arrays are for genuinely fixed sizes.

Indexing past the end

fn main() {
    let readings = [1, 2, 3];
    let index = 5;
    println!("{}", readings[index]); // panics at runtime
}

thread 'main' panicked at: index out of bounds: the len is 3 but the index is 5

Use `readings.get(index)` and handle the `None` case, or check the length first. Rust will not read past the end of the buffer either way.

Run it and change it

The editor below is live: edit anything and the real compiler output updates by itself.

Your Rust