Sub topic 11
Early return and the ? operator
This chapter assumes you can build and run a program with cargo. It also assumes you know Rust's primitive types, let and let mut, and how match and Result work at a basic level. You will learn how to leave a function early with return, and how the ? operator shortens error handling.
Early return with return
A function normally produces the value of its final expression. The return keyword leaves the function at once, from any depth, and supplies the result.
fn safe_div(a: i32, b: i32) -> Option<i32> {
if b == 0 {
return None;
}
Some(a / b)
}
fn main() {
println!("{:?}", safe_div(10, 2));
println!("{:?}", safe_div(1, 0));
}Handling the unusual case first and returning keeps the main path unindented. This style is called a guard clause. Note that return None; takes a semicolon, while the last expression Some(a / b) does not.
The problem: repeated matching
Result<T, E> is either Ok(value) or Err(error). Without help, each fallible call needs a match that forwards the error by hand.
use std::num::ParseIntError;
fn parse_and_double(s: &str) -> Result<i32, ParseIntError> {
let n: i32 = match s.trim().parse() {
Ok(n) => n,
Err(e) => return Err(e),
};
Ok(n * 2)
}
fn main() {
println!("{:?}", parse_and_double(" 21 "));
}This works, but the plumbing hides the logic. With several fallible calls the function becomes mostly match boilerplate.
The ? operator
Placing ? after an expression of type Result does the same thing as the match above. On Ok(v), the expression evaluates to v. On Err(e), the function returns Err(e) immediately.
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 first call prints Ok(42). The second prints Err(ParseIntError { kind: InvalidDigit }).
Where ? is allowed
The ? operator can only be used in a function whose return type can carry the failure. Using it in main with the default () return type is a compile error. You can give main a Result return type to fix that.
use std::num::ParseIntError;
fn main() -> Result<(), ParseIntError> {
let n: i32 = "42".parse()?;
println!("{n}");
Ok(())
}If main returns Err, the program prints the error and exits with a non-zero status code.
? also works on Option. A None makes the function return None. You cannot mix the two directly: using ? on an Option inside a function that returns Result does not compile.
fn first_char_upper(s: &str) -> Option<char> {
let c = s.chars().next()?;
Some(c.to_ascii_uppercase())
}
fn main() {
println!("{:?}", first_char_upper("rust"));
println!("{:?}", first_char_upper(""));
}Converting error types
When the error from the inner call differs from the function's error type, ? converts it using the From trait. It calls From::from on the error before returning. This lets one function use ? on several kinds of errors if the return type has a From implementation for each.
use std::fmt;
use std::num::ParseIntError;
#[derive(Debug)]
enum AppError {
Parse(ParseIntError),
Negative,
}
impl From<ParseIntError> for AppError {
fn from(e: ParseIntError) -> Self {
AppError::Parse(e)
}
}
impl fmt::Display for AppError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
AppError::Parse(e) => write!(f, "parse error: {e}"),
AppError::Negative => write!(f, "negative number"),
}
}
}
fn read_positive(s: &str) -> Result<i32, AppError> {
let n: i32 = s.parse()?;
if n < 0 {
return Err(AppError::Negative);
}
Ok(n)
}
fn main() {
for input in ["7", "-3", "x"] {
match read_positive(input) {
Ok(n) => println!("ok: {n}"),
Err(e) => println!("error: {e}"),
}
}
}Here s.parse()? turns a ParseIntError into AppError::Parse automatically, while the explicit return Err(...) handles the rule that parsing cannot check.
Common errors
| Mistake | Result | Fix |
|---|---|---|
| `?` in a function returning `()` | Compile error | Change the return type to `Result` or `Option` |
| `?` on `Option` in a `Result` function | Compile error | Use `ok_or(...)` to turn the `Option` into a `Result` |
| No `From` impl for the error type | Compile error | Implement `From`, or change the error type |
| Adding `;` after the final `Ok(n)` | Type mismatch: function returns `()` | Remove the semicolon |
Exercise
Write a function sum_two(a: &str, b: &str) -> Result<i32, ParseIntError> that parses both strings and returns their sum. What happens when a is "5" and b is "x"?
Show answer
Use let x: i32 = a.parse()?; let y: i32 = b.parse()?; Ok(x + y). The first ? succeeds with 5. The second ? sees Err from parsing "x", so the function returns that Err(ParseIntError { kind: InvalidDigit }) immediately and never reaches Ok(x + y).
Exercise
Why does let c = s.chars().next()?; fail to compile inside a function that returns Result<char, String>?
Show answer
next() returns an Option<char>, and ? on an Option can only return None, which is not a Result. Convert it first, for example s.chars().next().ok_or("empty string".to_string())?.