Sub topic 12
Common compiler errors and limits of ?
This chapter assumes you can read Result and Option signatures and have used ? in simple functions. You should also know that ? converts errors with the From trait. Here you will learn to read the compiler errors that ? produces, fix each one, and recognize where ? stops being the right tool.
The rule behind every error
? is shorthand for "unwrap on success, otherwise return early." The early return puts a value into the enclosing function's return type. So the compiler checks two things at every ?:
- The enclosing function, closure, or async block returns a type that
?can build:Result,Option, or another type that implements the required trait. - The residual (the
ErrorNonebeing returned) can be converted into that return type. ForResult, this meansFrom<SourceError>must exist for the target error type.
Every error below breaks one of these two checks.
Error 1: ? in a function that returns ()
This is the most common error, and it usually appears in main.
use std::fs;
// Does not compile: main returns ()
fn main() {
let text = fs::read_to_string("count.txt")?;
println!("{text}");
}The compiler reports something like this:
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)The function has no way to return an Err, so ? has nowhere to send it. You have three fixes.
- Change the return type, for example to
Result<(), Box<dyn std::error::Error>>. This is the usual fix formain. - Handle the error locally with
match,if let, orunwrap_or_else. - Move the fallible code into a helper function that returns
Result, and handle the error once in the caller.
use std::error::Error;
use std::fs;
fn main() -> Result<(), Box<dyn Error>> {
let text = fs::read_to_string("count.txt")?;
println!("{text}");
Ok(())
}Error 2: mixing Option and Result
? never converts between Option and Result on its own. The operand and the function return type must be in the same family.
// Does not compile: ? on an Option inside a function that returns Result
fn first_word_len(s: &str) -> Result<usize, String> {
let word = s.split_whitespace().next()?;
Ok(word.len())
}The compiler says the ? operator on an Option cannot be used in a function that returns Result. Decide what a missing value means as an error, and say so with ok_or or ok_or_else:
fn first_word_len(s: &str) -> Result<usize, String> {
let word = s.split_whitespace().next().ok_or("input is empty")?;
Ok(word.len())
}
fn main() {
println!("{:?}", first_word_len("hello world"));
println!("{:?}", first_word_len(" "));
}This prints Ok(5) and then Err("input is empty"). The ok_or call produces Result<&str, &str>. Then ? converts the &str error into String through the standard From<&str> for String implementation.
The reverse mistake is the same problem. Using ? on a Result inside a function that returns Option fails. Call .ok() first, which discards the error:
fn parse_double(s: &str) -> Option<i32> {
let n = s.parse::<i32>().ok()?;
Some(n * 2)
}
fn main() {
println!("{:?}", parse_double("21"));
println!("{:?}", parse_double("abc"));
}This prints Some(42) and then None. Use .ok() only when the caller does not need to know why the parse failed.
Error 3: no From conversion for the error type
When the function returns Result<T, MyError>, every ? on a Result<_, E> needs From<E> for MyError.
use std::num::ParseIntError;
#[derive(Debug)]
enum AppError {
Parse(ParseIntError),
}
// Does not compile: no From<ParseIntError> for AppError
fn parse(s: &str) -> Result<i32, AppError> {
let n = s.parse::<i32>()?;
Ok(n)
}error[E0277]: `?` couldn't convert the error to `AppError`
= help: the trait `From<ParseIntError>` is not implemented for `AppError`You can fix this in two ways. If every ParseIntError should become AppError::Parse, implement From once, as in the custom error chapter. If you want to decide at the call site, use map_err:
use std::num::ParseIntError;
#[derive(Debug)]
enum AppError {
Parse(ParseIntError),
}
fn parse(s: &str) -> Result<i32, AppError> {
let n = s.parse::<i32>().map_err(AppError::Parse)?;
Ok(n)
}
fn main() {
println!("{:?}", parse("12"));
println!("{:?}", parse("twelve"));
}The variant constructor AppError::Parse is itself a function from ParseIntError to AppError, so it can be passed to map_err directly. The ? still runs From, but the conversion from AppError to AppError is the identity.
Error 4: type annotations needed
? does not tell the compiler what type the unwrapped value has. If nothing else pins it down, inference fails:
use std::error::Error;
// Does not compile: the type of n is unknown
fn main() -> Result<(), Box<dyn Error>> {
let n = "5".parse()?;
println!("{n}");
Ok(())
}parse is generic over its output, and the error type also depends on that choice. With Box<dyn Error> as the target, many error types could convert, so the compiler cannot work backward. Annotate the variable or use a turbofish:
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
let n: i32 = "5".parse()?;
let m = "6".parse::<i32>()?;
println!("{}", n + m);
Ok(())
}Error 5: ? inside a closure
A closure has its own return type, separate from the function around it. A ? inside the closure returns from the closure, not from the function.
fn main() {
let items = ["1", "2", "x"];
// Does not compile: the closure returns i32, not Result
let nums: Vec<i32> = items.iter().map(|s| s.parse::<i32>()?).collect();
println!("{nums:?}");
}The compiler reports the same "can only be used in a function that returns Result or Option" message, but it points at the closure. Two fixes work. The first is to let the closure return the Result and collect into Result<Vec<_>, _>:
use std::num::ParseIntError;
fn main() {
let items = ["1", "2", "x"];
let nums: Result<Vec<i32>, ParseIntError> =
items.iter().map(|s| s.parse::<i32>()).collect();
println!("{nums:?}");
}The second is to use a plain for loop in the outer function, where ? returns from the function as you intended:
use std::num::ParseIntError;
fn sum_all(items: &[&str]) -> Result<i32, ParseIntError> {
let mut total = 0;
for s in items {
total += s.parse::<i32>()?;
}
Ok(total)
}
fn main() {
println!("{:?}", sum_all(&["1", "2", "3"]));
println!("{:?}", sum_all(&["1", "x", "3"]));
}The same rule applies to async blocks. Each block is its own return boundary, so a ? inside it needs a compatible type for that block, which often needs a type annotation on the final Ok.
Quick reference
| Symptom | Cause | Fix |
|---|---|---|
| `?` can only be used in a function that returns `Result` or `Option` | Enclosing function or closure returns `()` or another plain type | Change the return type, handle locally, or move code into a helper |
| `?` on an `Option` in a function returning `Result` | Mismatched families | `ok_or` or `ok_or_else` |
| `?` on a `Result` in a function returning `Option` | Mismatched families | `.ok()?` or a `match` |
| `From<E>` is not implemented for your error | No conversion defined | `impl From<E>` or `map_err` |
| Type annotations needed | `?` leaves the value type open | Annotate the binding or use a turbofish |
Limits of ?
Some problems compile fine but still show where ? is the wrong tool.
- It stops at the first error. If you want to validate every field of a form and report all problems,
?cannot help. Collect the errors yourself, for example by iterating and pushing failures into aVec. - It loses context when
Fromis too coarse. If two differentio::Errorsources both convert into the same variant, the caller cannot tell which operation failed. Usemap_errto attach a variant per call site, or add the path or key to the error value. - It does not log or recover.
?only returns. If a failure should trigger a retry or a default value, useunwrap_or,unwrap_or_else, ormatchwhere that decision belongs. - It does not catch panics.
?handles only values of typeResultandOption. Index out of bounds,unwraponNone, and arithmetic overflow in debug builds panic, and?never sees them. - Early exit skips later code. Cleanup that must run belongs in a
Dropimplementation, not after the?line.
Exercise
This function does not compile. Name the two reasons, then write a version that does. The function should return Err with a message when the string has no digits, and should convert a parse failure to a String error.
fn firstdigitvalue(s: &str) -> Result<u32, String> {
let c = s.chars().find(|c| c.isasciidigit())?;
let n = c.to_string().parse::<u32>()?;
Ok(n)
}
Show answer
The first ? is applied to an Option inside a function that returns Result, so it needs ok_or. The second ? yields a ParseIntError, and there is no From<ParseIntError> for String, so it needs map_err. A working version:
fn firstdigitvalue(s: &str) -> Result<u32, String> {
let c = s
.chars()
.find(|c| c.isasciidigit())
.okor("no digit found")?;
let n = c
.tostring()
.parse::<u32>()
.maperr(|e| e.tostring())?;
Ok(n)
}
A simpler alternative is c.to_digit(10).ok_or("not a digit")?, which avoids the string round trip.
Exercise
In a main that returns Result<(), Box<dyn Error>>, the line let n = "5".parse()?; fails to compile. Why, and what are two ways to fix it?
Show answer
? does not fix the type of n, and parse is generic over its output type, so the compiler cannot infer it. Fix it by annotating the binding (let n: i32 = "5".parse()?;) or by using a turbofish ("5".parse::<i32>()?).