Skip to content

Commit

Permalink
Improve tuple destructuring (#2582)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
djmitche authored Jan 23, 2025
1 parent b3734de commit 4ce87c5
Showing 1 changed file with 11 additions and 15 deletions.
26 changes: 11 additions & 15 deletions src/tuples-and-arrays/destructuring.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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 = tuple.0;
let right = tuple.1;
println!("left: {left}, right: {right}");
fn check_order(tuple: (i32, i32, i32)) -> bool {
let (left, middle, right) = tuple;
left < middle && middle < right
}
```
However, Rust also supports using pattern matching to destructure a larger value
into its constituent parts:

```rust,editable
fn print_tuple(tuple: (i32, i32)) {
let (left, right) = tuple;
println!("left: {left}, right: {right}");
fn main() {
let tuple = (1, 5, 3);
println!(
"{tuple:?}: {}",
if check_order(tuple) { "ordered" } else { "unordered" }
);
}
```

Expand Down

0 comments on commit 4ce87c5

Please sign in to comment.