Sub topic 4
Returning multiple values from functions
This chapter assumes you can write Rust functions, use Option and Result at a basic level, and know that a tuple is a fixed group of values with .0 and .1 access and let (a, b) = ... destructuring. Here you will use those tuple features to return more than one result from a function. You will also see where tuples stop being the right tool.
Why a tuple works as a return type
A Rust function has exactly one return value. To hand back several results, you return one value that contains them. A tuple is the lightest way to do this. It needs no type declaration, and the compiler checks the type of every position.
fn div_rem(a: i32, b: i32) -> Option<(i32, i32)> {
Some((a.checked_div(b)?, a.checked_rem(b)?))
}
fn main() {
let (q, r) = div_rem(17, 5).unwrap();
println!("q={q} r={r}");
println!("{:?}", div_rem(1, 0));
}The output is q=3 r=2, then None. The return type Option<(i32, i32)> reads as "maybe a pair of integers." The double parentheses in Some((..., ...)) are required. The outer pair belongs to Some, and the inner pair builds the tuple.
checked_div and checked_rem return None for a zero divisor. They also return None for the overflow case i32::MIN / -1, which would panic with plain /. The ? operator passes that None straight out of div_rem.
Three ways to take the result apart
A call that returns a tuple can be consumed in three ways.
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() {
let data = [3, 1, 4, 1, 5];
// 1. Keep the tuple and index it.
let pair = min_max(&data).unwrap();
println!("{} {}", pair.0, pair.1);
// 2. Destructure it right away.
if let Some((lo, hi)) = min_max(&data) {
println!("min={lo} max={hi}");
}
// 3. Keep only one part.
let (_, hi) = min_max(&data).unwrap();
println!("max only: {hi}");
}Use destructuring when the names carry meaning, because lo and hi read better than .0 and .1. Use _ to discard a position you do not need. The pattern must match the tuple's length exactly. Writing let (a, b, c) = min_max(&data).unwrap(); is a compile error ("expected a tuple with 2 elements, found one with 3 elements").
Ownership and borrowing in returned tuples
A tuple owns its elements, so returning a tuple can move values out of the function. That is the reason you can return a String this way.
A tuple can also hold references. In that case the usual lifetime rules apply. If the function has exactly one reference parameter, the compiler ties every returned reference to it.
fn split_name(full: &str) -> Option<(&str, &str)> {
full.split_once(' ')
}
fn main() {
match split_name("Ada Lovelace") {
Some((first, last)) => println!("{last}, {first}"),
None => println!("no space found"),
}
}This prints Lovelace, Ada. No data is copied, because both &str values point into the original string. If you return a reference to something created inside the function, the compiler rejects it because the local value is dropped at the end of the call. In that case, return an owned type such as String.
Combining tuples with Result and the ? operator
When a function can fail and also produces several values, put the tuple inside Ok.
fn parse_pair(line: &str) -> Result<(String, i32), String> {
let (key, value) = line
.split_once('=')
.ok_or_else(|| format!("missing '=' in {line:?}"))?;
let number = value
.trim()
.parse::<i32>()
.map_err(|e| format!("bad number {value:?}: {e}"))?;
Ok((key.trim().to_string(), number))
}
fn main() {
println!("{:?}", parse_pair("retries = 3"));
println!("{:?}", parse_pair("retries"));
println!("{:?}", parse_pair("retries = many"));
}The first call prints Ok(("retries", 3)). The other two print Err(...) with a message. Notice that split_once itself returns an Option<(&str, &str)>. The standard library uses this pattern widely.
Standard library functions that return tuples
You will meet tuple returns constantly, so recognise them.
| Function | Returns | Meaning |
|---|---|---|
| `slice.split_at(mid)` | `(&[T], &[T])` | Two slices, split at an index |
| `str.split_once(c)` | `Option<(&str, &str)>` | Text before and after the first match |
| `iter.partition(f)` | `(B, B)` | Items where `f` is true, then the rest |
| `iter.unzip()` | `(A, B)` | Two collections built from an iterator of pairs |
| `u32::overflowing_add(x)` | `(u32, bool)` | Wrapped result and an overflow flag |
fn main() {
let (evens, odds): (Vec<i32>, Vec<i32>) = (1..=6).partition(|n| n % 2 == 0);
println!("{evens:?} {odds:?}");
let (names, ages): (Vec<&str>, Vec<u32>) =
[("Ann", 31), ("Bo", 27)].into_iter().unzip();
println!("{names:?} {ages:?}");
}This prints [2, 4, 6] [1, 3, 5] and then ["Ann", "Bo"] [31, 27]. The type annotations on the left side tell partition and unzip which collections to build.
When a tuple stops being the right choice
Tuples have no field names. A signature like -> (f64, f64, f64) does not say what the numbers mean, and callers can swap two values of the same type without any compiler error. Consider a struct when any of these hold:
- There are more than about three values.
- Two or more values share a type, so they could be mixed up.
- The result is passed around or stored, not consumed on the spot.
- You want to add methods or documentation to the result.
struct Stats {
min: i32,
max: i32,
mean: f64,
}
fn stats(values: &[i32]) -> Option<Stats> {
let first = *values.first()?;
let (mut min, mut max, mut total) = (first, first, 0i64);
for &v in values {
min = min.min(v);
max = max.max(v);
total += i64::from(v);
}
Some(Stats { min, max, mean: total as f64 / values.len() as f64 })
}
fn main() {
if let Some(s) = stats(&[3, 1, 4, 1, 5]) {
println!("{} {} {:.1}", s.min, s.max, s.mean);
}
}This prints 1 5 2.8. The call site now reads s.mean instead of .2, and the compiler will not let you confuse min with max.
Common errors
- Arity mismatch.
let (a, b) = f();fails whenfreturns three values. Count the positions. - Missing inner parentheses.
Some(a, b)is an error, becauseSometakes one argument. WriteSome((a, b)). - Using
.0on anOption.min_max(&data).0does not compile, since theOptionis not the tuple. Unwrap or match first. - Returning a reference to a local. Return an owned value instead.
Exercise
A function returns Result<(u32, u32), String>. Write the line that calls it with ? and splits the success value into width and height, assuming the function is named read_size and takes no arguments. Why would a struct be a better return type if the function also returned a third u32?
Show answer
let (width, height) = read_size()?; The ? unwraps the Ok value or returns the Err early, and the pattern splits the tuple. With a third u32, three values of the same type are easy to swap silently, and .2 carries no meaning. A struct with named fields such as width, height and depth makes call sites self-documenting and lets the compiler catch mix-ups.
Exercise
What is the type of the value returned by (1..=4).partition(|n| n % 2 == 0) if you annotate the result as a pair of Vec<i32>, and what does it contain?
Show answer
(Vec<i32>, Vec<i32>). The first vector holds the items for which the closure returned true, which is [2, 4]. The second holds the rest, which is [1, 3].