Rust Fundamentals · 15 XP Pro
Tuples
A tuple groups a fixed number of values, which may have different types.
The type is written like the value: (i32, f64, char).
let point: (i32, i32) = (3, -4);
let first = point.0; // access by position
let second = point.1;
You can also destructure a tuple, pulling it apart into separate variables
with a pattern on the left of let:
let (x, y) = point;
println!("x = {x}, y = {y}");
Destructuring works in function parameters too: fn norm((x, y): (i32, i32)).
Tuples are Rust's simplest way to return several values from one function:
fn min_max(a: i32, b: i32) -> (i32, i32) {
if a < b { (a, b) } else { (b, a) }
}
let (low, high) = min_max(9, 2);
The empty tuple () is the "unit" type you met with the missing semicolon.
Your task
Write these public functions:
divmod(a: u32, b: u32) -> (u32, u32)returns the quotient and the remainder ofa / b. You may assumebis not zero.divmod(17, 5)is(3, 2).swap_pair(pair: (i32, f64)) -> (f64, i32)returns the two values in reversed order. Destructure the argument.distance_squared(p: (i32, i32), q: (i32, i32)) -> i32returns(px - qx)^2 + (py - qy)^2. Destructure both points.