Tsallaka zuwa abun ciki
Justice Tech School

Returning Tuples and Early Returns

Return several values as a tuple, and use return for early exits. Destructure the result at the call site.

Example
fn min_max(v: &[i32]) -> (i32, i32) {
    let mut lo = v[0];
    let mut hi = v[0];
    for &x in v { if x < lo { lo = x; } if x > hi { hi = x; } }
    (lo, hi)
}
fn main() {
    let (lo, hi) = min_max(&[3, 9, 1, 7]);
    println!("{} {}", lo, hi);
}

Result

1 9

Exercise

Leave a function early.

 0;

Quiz Test

How do you return two values?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.