Sub topic 4
Returning multiple values from functions
This chapter assumes you can write basic Rust functions, build tuples, and destructure them with let (a, b) = pair;. It also assumes you know that Option represents a value that may be missing.
One return value, many results
A Rust function returns exactly one value. To hand back several results, return one tuple. The return type lists each element type in parentheses, and the body ends with a tuple expression.
The next example finds the smallest and largest values in a slice. It returns Option<(i32, i32)> because an empty slice has no minimum or maximum.
fn min_max(values: &[i32]) -> Option<(i32, i32)> {
let first = *values.first()?;
let mut min = first;
let mut max = first;
for &v in &values[1..] {
if v < min {
min = v;
}
if v > max {
max = v;
}
}
Some((min, max))
}
fn main() {
if let Some((lo, hi)) = min_max(&[3, 1, 4, 1, 5]) {
println!("min={lo} max={hi}");
}
println!("{:?}", min_max(&[]));
}Three details matter here:
values.first()returnsOption<&i32>. The?operator returnsNonefrommin_maxright away when the slice is empty, so the rest of the function can assume at least one element.Some((min, max))has two pairs of parentheses. The inner pair builds the tuple, and the outer pair is theSomeconstructor.- The caller destructures inside the
if letpattern, soloandhiare named at the point of use.
Ignoring part of the result
When you need only one value, use _ in the pattern. You can also read a field by index.
fn div_rem(a: u32, b: u32) -> (u32, u32) {
(a / b, a % b)
}
fn main() {
let (quotient, remainder) = div_rem(17, 5);
println!("{quotient} r {remainder}");
let (_, only_remainder) = div_rem(17, 5);
println!("{only_remainder}");
println!("{}", div_rem(17, 5).0);
}Dividing by zero panics for integers, so div_rem(1, 0) would crash. A production version would return an Option or Result.
Common errors
- Wrong number of names.
let (a, b, c) = div_rem(17, 5);fails with a mismatched types error. The pattern must have the same number of elements as the tuple. - A stray semicolon. Writing
(a / b, a % b);as the last line turns the tuple into a statement. The function then returns(), and the compiler reports a mismatch with the declared return type. - Unreadable positions. A caller seeing
result.0andresult.1cannot tell what they mean. This gets worse when both elements have the same type, such as(i32, i32), because swapping them compiles without complaint.
When to switch to a struct
Tuples suit two or three results that are obvious from the function name. Once you have more than that, or elements of the same type that are easy to confuse, define a struct with named fields. Callers then write stats.max instead of stats.1.
Exercise
Write a function sum_and_count(values: &[i32]) -> (i32, usize) that returns the sum of the values and how many there are. How do you print only the count at the call site?
Show answer
fn sumandcount(values: &[i32]) -> (i32, usize) { (values.iter().sum(), values.len()) }. At the call site, write let (_, count) = sum_and_count(&[4, 5, 6]); println!("{count}");, which prints 3. The _ discards the sum.