Tuples and arrays
Tuples and arrays hold more than one value in a single variable.
Tuples
A tuple groups a few values, and each one can have a different type. Read a value with a dot and its position, starting at 0.
let t = (1, true, 'x');println!("{}", t.0); // 1println!("{}", t.2); // xYou can also unpack a tuple into separate variables. This is called destructuring.
let (a, b) = (5, "five");println!("{b} is {a}");Arrays
An array holds a fixed number of values, all of the same type. Its type is written [T; N]: the element type, then the length.
let a = [1, 2, 3]; // [i32; 3]let zeros = [0; 4]; // [0, 0, 0, 0]An array can't grow or shrink. Mixing types, like [1, "two"], is an error. Print a whole array with {:?}, like println!("{a:?}").
### Vectors
A Vec is like an array that can grow. Make one with vec![...]; its type is written Vec<i32>. v.push(x) adds a value at the end, so the Vec must be let mut. v.len() gives its length, just like an array.
let mut v = vec![1, 2];v.push(3);println!("{v:?}"); // [1, 2, 3]Indexing and len
Read one element with a[i]. Indexes start at 0, so the last index is the length minus 1. a.len() gives the length as a usize. A usize is an unsigned whole number used for sizes and indexes.
let a = [10, 20, 30];println!("{}", a[1]); // 20println!("{}", a.len()); // 3To change an element, the array must be mut: a[0] = 9;.
Type annotations
Rust works out most types for you. You can still write a type after the name with a colon.
let x: u8 = 5;let pair: (i32, bool) = (1, true);let nums: [u32; 3] = [7, 8, 9];If the value does not fit the type you wrote, Rust stops with error E0308, "mismatched types".
Remember
- Tuples use
t.0; arrays usea[0]. - Both start counting at 0.
- An array's length is part of its type.
- E0308 means a value's type is not the one Rust expected.