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
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 tupleslet person: (&str, i32, bool) = ("Alice", 30, true);let mixed = (42, 3.14, 'A', "text");// Accessing elements by indexprintln!("Age: {}", person.1);// Destructuring with letlet (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 parametersprint_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