1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-03-20 14:31:15 +02:00

Improve tuple destructuring (#2582)

This slide had two code samples, neither of which had a `main` and thus
neither of which would run. This removes the first (which is redundant
to one a few slides earlier), adds a `main`, and expands the second to
use a 3-tuple.
This commit is contained in:
Dustin J. Mitchell 2025-01-23 09:23:08 -05:00 committed by GitHub
parent b3734de08b
commit 4ce87c5473
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -4,25 +4,21 @@ minutes: 5
# Patterns and Destructuring
When working with tuples and other structured values it's common to want to
extract the inner values into local variables. This can be done manually by
directly accessing the inner values:
```rust,editable
fn print_tuple(tuple: (i32, i32)) {
let left = tuple.0;
let right = tuple.1;
println!("left: {left}, right: {right}");
}
```
However, Rust also supports using pattern matching to destructure a larger value
Rust supports using pattern matching to destructure a larger value like a tuple
into its constituent parts:
```rust,editable
fn print_tuple(tuple: (i32, i32)) {
let (left, right) = tuple;
println!("left: {left}, right: {right}");
fn check_order(tuple: (i32, i32, i32)) -> bool {
let (left, middle, right) = tuple;
left < middle && middle < right
}
fn main() {
let tuple = (1, 5, 3);
println!(
"{tuple:?}: {}",
if check_order(tuple) { "ordered" } else { "unordered" }
);
}
```