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?
let tuple = (10, 20, 30); let (a, b, c) = tuple; println!("{} {} {}", a, b, c);
Remember that tuple destructuring assigns values in order.
The tuple (10, 20, 30) is destructured into variables a, b, and c respectively. So a = 10, b = 20, c = 30.
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?
struct Point { x: i32, y: i32 }
let p = Point { x: 5, y: 10 };
let Point { x: a, y: b } = p;
println!("{} {}", a, b);Destructuring assigns fields to new variable names.
The struct fields x and y are assigned to variables a and b respectively, so a = 5 and b = 10.
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?
let data = (Some(3), Ok(7)); let (Some(x), Ok(y)) = data; println!("{} {}", x, y);
Remember that pattern matching can destructure enum variants.
The tuple contains Some(3) and Ok(7). The pattern matches and extracts 3 into x and 7 into y.
Consider this Rust code snippet:
let tuple = (1, 2);
let (a, b, c) = tuple;
println!("{} {} {}", a, b, c);What error will this code produce?
let tuple = (1, 2); let (a, b, c) = tuple; println!("{} {} {}", a, b, c);
Check the number of elements in the tuple and pattern.
The pattern expects 3 elements but the tuple has only 2, causing a compile-time error.
Given this Rust pattern:
let (a, (b, c), d) = (1, (2, 3), 4);
How many variables are bound after this destructuring?
let (a, (b, c), d) = (1, (2, 3), 4);
Count each variable name on the left side of the assignment.
The pattern binds variables a, b, c, and d. That is 4 variables total.