Click a card to flip it · 13 terms
A tuple groups values of different types into a single compound value. This deck covers creating tuples, accessing elements with dot notation, and unpacking them with destructuring.
A group of values of different types bundled together, fixed size.
Packaging a few related values of different types into one variable.
let sub = ("Alice", 25, true);
The written type of a tuple: types listed in parentheses separated by commas.
When Rust needs to know explicitly what types the tuple holds.
let data: (&str, u64, bool) = ("Alice", 1_000_000, true);
Tuple elements are counted from 0, not 1. The first element is index 0.
Every time you access an element with dot notation.
let t = (10, 20, 30);t.0 // 10, not t.1
Access a specific element in a tuple using .0, .1, .2 etc.
Reading one value out of a tuple by its position.
let point = (4, 7);let x = point.0; // 4let y = point.1; // 7
A tuple that contains another tuple as one of its elements.
When you need a compound structure without writing a full struct.
let nested = (1u8, (2i32, 3i32));let inner_y = nested.1.1; // 3
Pulling all values out of a tuple at once and assigning each to its own variable.
When you want to work with each part of a tuple separately.
let (name, age, active) = sub;// no dot notation needed
The empty tuple. Rust's way of saying a function returns nothing meaningful.
The implicit return type when a function has no return statement.
fn log(msg: &str) { // returns () println!("{}", msg);}
A struct defined with positional (unnamed) fields, looks like a tuple with a name.
When you want a named type but don't need field names.
struct Wallet(String, u64);let w = Wallet("abc".to_string(), 1000);
Using _ in destructuring to skip elements you don't need.
When you only care about some values in a tuple.
let (name, _) = get_user();// age is ignored
A tuple declared with mut, allowing its fields to be reassigned.
When you need to update one of the tuple's values after creation.
let mut point = (0, 0);point.0 = 5; // now (5, 0)
Functions can return multiple values by returning a tuple.
When you need to hand back two or more values from one function call.
fn bounds(v: &[i32]) -> (i32, i32) { (v[0], v[v.len()-1])}
Using a match statement to branch on tuple values.
When multiple combinations of values lead to different behavior.
match point { (0, 0) => "origin", _ => "other"}
Tuples use positional access (.0, .1). Structs use named fields (.name, .age). Same data, different readability.
Tuples are quick for small ad-hoc groups. Structs are clearer when fields have meaning.
tuple: (name, age) vs struct: User { name, age }