0
0
Rustprogramming~20 mins

Destructuring patterns in Rust - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Rust Destructuring Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this tuple destructuring?

Consider the following Rust code that uses tuple destructuring:

let tuple = (10, 20, 30);
let (a, b, c) = tuple;
println!("{} {} {}", a, b, c);

What will be printed?

Rust
let tuple = (10, 20, 30);
let (a, b, c) = tuple;
println!("{} {} {}", a, b, c);
A10 30 20
B30 20 10
C10 20 30
DCompilation error due to mismatched types
Attempts:
2 left
💡 Hint

Remember that tuple destructuring assigns values in order.

Predict Output
intermediate
2:00remaining
What does this struct destructuring print?

Given this Rust code with a struct and destructuring:

struct Point { x: i32, y: i32 }

let p = Point { x: 5, y: 10 };
let Point { x: a, y: b } = p;
println!("{} {}", a, b);

What is the output?

Rust
struct Point { x: i32, y: i32 }

let p = Point { x: 5, y: 10 };
let Point { x: a, y: b } = p;
println!("{} {}", a, b);
A5 10
B10 5
CCompilation error: cannot destructure struct
D0 0
Attempts:
2 left
💡 Hint

Destructuring assigns fields to new variable names.

Predict Output
advanced
2:00remaining
What is printed by this nested destructuring?

Analyze this Rust code with nested destructuring:

let data = (Some(3), Ok(7));
let (Some(x), Ok(y)) = data;
println!("{} {}", x, y);

What will be printed?

Rust
let data = (Some(3), Ok(7));
let (Some(x), Ok(y)) = data;
println!("{} {}", x, y);
A3 7
BSome(3) Ok(7)
CCompilation error: cannot destructure enums this way
DRuntime panic due to pattern mismatch
Attempts:
2 left
💡 Hint

Remember that pattern matching can destructure enum variants.

Predict Output
advanced
2:00remaining
What error does this destructuring cause?

Consider this Rust code snippet:

let tuple = (1, 2);
let (a, b, c) = tuple;
println!("{} {} {}", a, b, c);

What error will this code produce?

Rust
let tuple = (1, 2);
let (a, b, c) = tuple;
println!("{} {} {}", a, b, c);
Aerror: variable c is unused
Berror: mismatched tuple size: expected a 3-element tuple but found a 2-element tuple
Cprints: 1 2 0
Dcompiles and prints: 1 2 3
Attempts:
2 left
💡 Hint

Check the number of elements in the tuple and pattern.

🧠 Conceptual
expert
2:00remaining
How many variables are bound in this pattern?

Given this Rust pattern:

let (a, (b, c), d) = (1, (2, 3), 4);

How many variables are bound after this destructuring?

Rust
let (a, (b, c), d) = (1, (2, 3), 4);
A3
B5
C2
D4
Attempts:
2 left
💡 Hint

Count each variable name on the left side of the assignment.