let (name, age, is_active) = person;
println!("Name: {}", name);
println!("Age: {}", age);
println!("Is Active: {}", is_active);
}
In this example, both indexing (person.0, person.1, person.2) and
destructuring (let (name, age, is_active) = person) are used to access
and print individual elements of the tuple.
Common Operations: Pattern Matching and Returning Tuples
Tuples can also be used in pattern matching and as return values from
functions. Pattern matching allows developers to match against
specific tuple patterns, while returning tuples enables functions to
return multiple values conveniently.
fn main() {
let person = ("Alice", 30, true);
// Pattern matching with tuples
match person {
(name, age, true) => println!("{} is {} years old and active", name, age),
(name, age, false) => println!("{} is {} years old and inactive", name, age),
}
// Function returning a tuple
fn get_person() -> (String, u32, bool) {
("Bob".to_string(), 25, false)
}
let (name, age, is_active) = get_person();
println!("Name: {}, Age: {}, Is Active: {}", name, age, is_active);
}
In this example, pattern matching is used to match against different
states of activity in the tuple, and a function get_person returns a
tuple containing information about a person.
Tuples provide a convenient way to group together heterogeneous
data in Rust. By understanding how to create, access, and manipulate
tuples, developers can effectively work with composite data
structures in their Rust programs.