Sub topic 11
Early return and the ? operator
This chapter assumes you can write functions with typed parameters and return values, you know match, and you know that Option and Result are enums. You do not need to have written your own error types yet. By the end you will know how return and ? leave a function early, what ? expands to, and how to fix the usual type errors around it.
Early return with return
A function normally returns the value of its last expression. The return keyword leaves the function at once, from any depth of nesting, and supplies the value.
fn find_negative(values: &[i32]) -> Option<usize> {
for (i, &v) in values.iter().enumerate() {
if v < 0 {
return Some(i);
}
}
None
}
fn main() {
println!("{:?}", find_negative(&[3, 8, -2, 5]));
println!("{:?}", find_negative(&[1, 2]));
}This prints Some(2) and then None. return inside the for loop exits the whole function, not only the loop. The final None has no semicolon, so it is the value of the normal path.
Use early return for guard checks at the top of a function. Handling the failure cases first keeps the main logic at one level of indentation instead of inside nested if blocks.
Why ? exists
Functions that can fail return Result<T, E>. Without help, every fallible call needs a match that unwraps Ok or returns the Err:
use std::num::ParseIntError;
fn parse_and_double(s: &str) -> Result<i32, ParseIntError> {
let n: i32 = match s.trim().parse::<i32>() {
Ok(value) => value,
Err(e) => return Err(e),
};
Ok(n * 2)
}
fn main() {
println!("{:?}", parse_and_double(" 21 "));
println!("{:?}", parse_and_double("abc"));
}The ? operator replaces that whole match. Place it after an expression of type Result:
use std::num::ParseIntError;
fn parse_and_double(s: &str) -> Result<i32, ParseIntError> {
let n: i32 = s.trim().parse()?;
Ok(n * 2)
}
fn main() {
println!("{:?}", parse_and_double(" 21 "));
println!("{:?}", parse_and_double("abc"));
}The output is Ok(42) and then Err(ParseIntError { kind: InvalidDigit }). If the value is Ok(v), the expression expr? evaluates to v. If it is Err(e), the function returns Err(e) immediately, so the code after the ? does not run.
What ? expands to
Roughly, expr? behaves like this:
let n = match expr {
Ok(v) => v,
Err(e) => return Err(From::from(e)),
};The detail that matters is From::from(e). The error is converted into the function's declared error type, so the error type of the called function does not have to match the error type of the caller. It only needs a From conversion into it. When the two types are identical, the conversion does nothing.
Converting errors with From
Most real functions call several operations that fail in different ways. A common pattern is an enum with one variant per failure, plus a From implementation for each error type that ? should convert.
use std::num::ParseIntError;
#[derive(Debug)]
enum ConfigError {
MissingPort,
BadNumber(ParseIntError),
}
impl From<ParseIntError> for ConfigError {
fn from(e: ParseIntError) -> Self {
ConfigError::BadNumber(e)
}
}
fn read_port(text: &str) -> Result<u16, ConfigError> {
let line = text
.lines()
.find(|l| l.starts_with("port="))
.ok_or(ConfigError::MissingPort)?;
let port = line["port=".len()..].trim().parse::<u16>()?;
Ok(port)
}
fn main() -> Result<(), ConfigError> {
println!("{:?}", read_port("host=a\nport=8080"));
println!("{:?}", read_port("host=a"));
println!("{}", read_port("port=abc")?);
Ok(())
}The first ? needs no conversion because ok_or already produced a ConfigError. The second ? sees a ParseIntError, finds impl From<ParseIntError> for ConfigError, and wraps it as BadNumber.
The program prints Ok(8080) and Err(MissingPort). The third call fails, so main returns the error, and the runtime prints Error: BadNumber(ParseIntError { kind: InvalidDigit }) to standard error and exits with a nonzero status.
Using Box<dyn Error> when you don't need your own type
For small programs and prototypes, you can skip the custom enum. Any type that implements the Error trait converts into Box<dyn Error>, and so do string slices.
use std::error::Error;
fn sum_line(line: &str) -> Result<i32, Box<dyn Error>> {
let mut total = 0;
for part in line.split(',') {
total += part.trim().parse::<i32>()?;
}
if total < 0 {
return Err("negative total".into());
}
Ok(total)
}
fn main() {
println!("{:?}", sum_line("1, 2, 3"));
println!("{:?}", sum_line("1, x"));
println!("{:?}", sum_line("-5, 1"));
}This example uses both mechanisms. ? converts a ParseIntError into the box, and "negative total".into() converts a string into one. The trade-off is that callers lose the ability to match on specific error variants. Prefer a custom enum in library code, where callers may need to react to each failure differently.
? on Option
? also works on Option. Some(v) becomes v, and None makes the function return None.
fn first_even_square(values: &[i32]) -> Option<i32> {
let first = values.iter().find(|&&v| v % 2 == 0)?;
Some(first * first)
}
fn main() {
println!("{:?}", first_even_square(&[3, 4, 6]));
println!("{:?}", first_even_square(&[3, 5]));
}The output is Some(16) and then None. There is no error value to convert, so From is not involved.
| Expression type | Function must return | On the failure case |
|---|---|---|
| `Result<T, E>` | `Result<U, F>` where `F: From<E>` | returns `Err(From::from(e))` |
| `Option<T>` | `Option<U>` | returns `None` |
Common errors
Using ? in a function that returns ()
This is the most frequent mistake. A function with no return type returns (), which cannot hold an error, so the compiler rejects ? there. The message says the ? operator can only be used in a function that returns Result or Option. Change the return type to Result<(), E> and end the body with Ok(()).
Mixing Option and Result
? does not convert between Option and Result. If a function returns Result and you apply ? to an Option, you get a type error. Convert with ok_or or ok_or_else first, as read_port did. The reverse direction uses .ok(), which turns Result<T, E> into Option<T> and discards the error.
Missing From implementation
If the callee's error type has no From conversion into your error type, the compiler reports that ? couldn't convert the error. Either add the impl From, change the return type to Box<dyn Error>, or convert explicitly with map_err:
fn parse_port(s: &str) -> Result<u16, String> {
s.parse::<u16>().map_err(|e| format!("bad port {s:?}: {e}"))
}
fn main() {
println!("{:?}", parse_port("80"));
println!("{:?}", parse_port("99999"));
}? inside closures
? returns from the nearest enclosing function or closure, not from the function that contains the closure. A closure that uses ? must itself return Result or Option. A useful result of this rule is that you can collect an iterator of Result values into one Result, which stops at the first error:
fn parse_all(items: &[&str]) -> Result<Vec<i32>, std::num::ParseIntError> {
items.iter().map(|s| s.parse::<i32>()).collect()
}
fn main() {
println!("{:?}", parse_all(&["1", "2", "3"]));
println!("{:?}", parse_all(&["1", "two", "3"]));
}Choosing between return, ?, match, and let-else
- Use
?when the right response to a failure is to hand it to the caller unchanged, apart from conversion. - Use
matchwhen you need to handle the failure locally, for example by supplying a default or retrying. - Use
let ... elsewhen you want to bind a value or return a specific value of your own, as inlet Some(x) = opt else { return 0; };. - Use plain
returnfor guard conditions that are not aboutOptionorResult.
Exercise
The function below fails to compile. Why, and how do you fix it? fn first_char_upper(s: &str) -> Result<char, String> { let c = s.chars().next()?; Ok(c.to_ascii_uppercase()) }
Show answer
s.chars().next() returns an Option<char>, but the function returns a Result, and ? does not convert between the two. Convert the Option first, with an error message: let c = s.chars().next().ok_or("empty string".to_string())?;. The String error then matches the declared return type.
Exercise
Given fn load(s: &str) -> Result<i32, MyError> that uses s.parse::<i32>()?, what must exist for this to compile, and what does ? do when the parse fails?
Show answer
MyError must implement From<ParseIntError>. When the parse fails, ? calls From::from on the ParseIntError to produce a MyError and returns Err(that_error) from load immediately. The statements after the ? do not run.