0
0
Rustprogramming~10 mins

Destructuring patterns in Rust - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to destructure the tuple and print the first value.

Rust
let tuple = (10, 20);
let ([1], _) = tuple;
println!("{}", first);
Drag options to blanks, or click blank then click option'
Ax
Bfirst
Ca
Dval
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name different from the one in println! causes a compile error.
Trying to destructure without parentheses.
2fill in blank
medium

Complete the code to destructure the struct and print the name field.

Rust
struct Person { name: String, age: u8 }
let person = Person { name: String::from("Alice"), age: 30 };
let Person { [1], age: _ } = person;
println!("{}", name);
Drag options to blanks, or click blank then click option'
Aname
Bage
Cperson
Dvalue
Attempts:
3 left
💡 Hint
Common Mistakes
Using the struct name instead of the field name in the pattern.
Forgetting to ignore the unused field with underscore.
3fill in blank
hard

Fix the error in the code by completing the pattern to destructure the enum variant.

Rust
enum Message {
    Quit,
    Move { x: i32, y: i32 },
}
let msg = Message::Move { x: 5, y: 10 };
match msg {
    Message::Move [1] => println!("x: {}, y: {}", x, y),
    _ => (),
}
Drag options to blanks, or click blank then click option'
Ax, y
B(x, y)
C{ x, y }
D[x, y]
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses or brackets instead of curly braces for named fields.
Not matching the field names exactly.
4fill in blank
hard

Fill both blanks to destructure the nested tuple and print the inner values.

Rust
let nested = ((1, 2), (3, 4));
let ([1], [2]) = nested;
println!("{} {}", a, b);
Drag options to blanks, or click blank then click option'
A(a, b)
Bx
Cy
D(c, d)
Attempts:
3 left
💡 Hint
Common Mistakes
Using variable names without parentheses for tuple patterns.
Not matching the nested structure correctly.
5fill in blank
hard

Fill all three blanks to destructure a tuple and filter values greater than 5 in a comprehension.

Rust
let numbers = vec![(1, 6), (3, 4), (7, 8)];
let filtered: Vec<_> = numbers.iter()
    .filter(|&&([1], [2])| [3] > 5)
    .collect();
Drag options to blanks, or click blank then click option'
Ax
By
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong variable in the filter condition.
Not destructuring the tuple correctly.