capypad
0 day streak
rust / beginner
Snippet

Tuple Creation and Destructuring

Tuples in Rust are fixed-size collections that can hold values of different types. Each element is accessed by its position (index starting at 0). Tuples can be destructured using pattern matching with let statements, allowing you to extract individual values into separate variables. The underscore _ pattern lets you ignore unwanted values.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
fn main() {
// Creating tuples
let person: (&str, i32, bool) = ("Alice", 30, true);
let mixed = (42, 3.14, 'A', "text");
// Accessing elements by index
println!("Age: {}", person.1);
// Destructuring with let
let (name, age, is_student) = person;
println!("{} is {} years old", name, age);
// Ignoring tuple elements with _
let (num, _, char_val, _) = mixed;
println!("Number: {}, Char: {}", num, char_val);
// Destructuring in function parameters
print_coordinates(&(10, 20));
}
 
fn print_coordinates(point: &(i32, i32)) {
let (x, y) = point;
println!("X: {}, Y: {}", x, y);
}
Breakdown
1
let person: (&str, i32, bool)
Typed tuple with string, integer, and boolean
2
person.1
Accesses the second element (age) by index
3
let (name, age, is_student) = person;
Destructures tuple into three separate variables
4
let (num, _, char_val, _) = mixed;
Destructures while ignoring elements with underscore