rust / beginner
Snippet
Tuples: Grouping Mixed Types
Tuples allow you to group multiple values of different types into a single compound type. Access elements using dot notation (data.0, data.1) or destructure them with pattern matching. The underscore _ ignores a value you don't need.
snippet.rs
1
2
3
4
5
6
7
8
9
fn main() {let data: (&str, i32, bool) = ("Rust", 2024, true);println!("Language: {}", data.0);println!("Year: {}", data.1);println!("IsAwesome: {}", data.2);let (lang, year, _) = data;println!("Destructured: {} in {}", lang, year);}
Breakdown
1
let data: (&str, i32, bool)
Declares a tuple with three elements: a string slice, an integer, and a boolean. Type annotation is required when types can't be inferred.
2
data.0, data.1, data.2
Access tuple elements by their index starting at 0.
3
let (lang, year, _) = data
Destructuring pattern that extracts values into separate variables. The _ silently discards that value.