Sub topic 12
Common compiler errors and limits of ?
This chapter assumes you know Result and Option, can write a function that uses ?, and understand the From trait. Here you will learn the compiler errors that ? causes most often, and the places where ? cannot be used.
The rule behind every error
? returns early from the enclosing function. So the function's return type must be able to hold the early value. Two checks happen at each ?:
- The return type must be a kind that
?supports, such asResult,Option, orPoll. - The error (or
None) must convert into what the return type expects.
Most ? errors break one of these two checks.
Error 1: using ? in a function that returns ()
This is the most common mistake, especially in main and in small test scripts.
use std::fs;
fn main() {
let text = fs::read_to_string("count.txt")?;
println!("{text}");
}The compiler reports that the ? operator can only be used in a function that returns Result or Option. The function returns (), so there is nowhere to send the error.
You have two fixes. Change the signature, as in the main chapter, to fn main() -> Result<(), Box<dyn std::error::Error>>. Or handle the error locally with match, unwrap_or, or expect.
The same error appears inside closures. A closure has its own return type, so a ? inside it applies to the closure, not to the function around it.
fn parse_all(items: &[&str]) -> Result<Vec<i32>, std::num::ParseIntError> {
items.iter().map(|s| s.parse::<i32>()).collect()
}Here the closure returns a Result and collect combines the results. Writing s.parse::<i32>()? inside the closure would not make the outer function return early.
Error 2: mixing Option and Result
A ? on an Option needs a function that returns Option. A ? on a Result needs a function that returns Result. Rust does not convert between them automatically.
fn first_number(s: &str) -> Result<i32, String> {
let word = s.split_whitespace().next()?; // error: Option in a Result function
word.parse::<i32>().map_err(|e| e.to_string())
}The compiler says the ? operator on an Option cannot be used in a function that returns Result. Convert the Option first:
fn first_number(s: &str) -> Result<i32, String> {
let word = s
.split_whitespace()
.next()
.ok_or_else(|| "empty input".to_string())?;
word.parse::<i32>().map_err(|e| e.to_string())
}Going the other way, .ok() turns a Result into an Option and discards the error.
Error 3: no From conversion between error types
If the function's error type is not the same as the operand's error type, ? calls From::from. If no From implementation exists, you get an error like `the trait From<ParseIntError> is not implemented for String `.
fn parse_port(s: &str) -> Result<u16, String> {
let port = s.parse::<u16>()?; // error: no From<ParseIntError> for String
Ok(port)
}You can fix it in three ways:
- Convert at the call site with
map_err, as above:.map_err(|e| e.to_string())?. - Implement
From<ParseIntError>for your own error type. - Return
Box<dyn Error>, which accepts any type that implementsError.
A String error type is a poor long-term choice because String does not implement Error. That is why ? cannot convert into it automatically.
Limits of ?
| Situation | What happens | Workaround |
|---|---|---|
| Function returns `()` | Compile error | Return `Result`, or handle locally |
| Inside a closure | Applies to the closure only | Give the closure a `Result` return type |
| `Option` in a `Result` function | Compile error | `ok_or` or `ok_or_else` |
| Unrelated error types | Missing `From` | `map_err`, `From` impl, or `Box<dyn Error>` |
| Type inference fails with `Box<dyn Error>` | Ambiguity error | Annotate the type |
Reading the messages
Start with the first error in the output and read the line marked with ?. It names the function's return type and the operand's type. Compare the two. Nearly every fix is one of the three conversions above.
Exercise
This function fails to compile. Why, and what is the smallest fix? fn lenoffirst(items: &[String]) -> Result<usize, String> { let first = items.first()?; Ok(first.len()) }
Show answer
items.first() returns an Option, but the function returns a Result, so ? cannot be used on it. Convert the Option with ok_or: let first = items.first().ok_or("no items".to_string())?;. The error type is now String, which matches the function's return type.
Exercise
A closure passed to for_each uses ? and the compiler complains that the closure returns (). What are two ways to fix it?
Show answer
Give the closure a Result return type and end it with Ok(()), then handle the result of the whole iteration, for example with try_for_each. Or use a plain for loop in the enclosing function, where ? returns from that function.