Terminology (4)Terms used in this lesson
Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.
- ? with Result
- Produces the Ok value or returns the converted Err at the enclosing propagation boundary.
- From conversion
- An implementation that maps the source error into the receiving error type in the shown Result path.
- ok_or / ok_or_else
- Convert Option to Result using an evaluated error value or a closure invoked only for None.
- Collect into Result
- Collects successful values or stops at the first Err; later iterator elements are not requested after failure.
Result connects values and control flow
Result<T, E> separates a successful T from a failure E. In the Result-returning functions here, ? extracts Ok or returns Err through a compatible error conversion. The receiving function’s error type and its From implementations determine that conversion; returning Err remains distinct from panicking.
Option expresses presence or absence, so converting it to Result requires a chosen error for the missing case. Combinators also determine when fallback work runs and whether failed items remain visible to the caller. Check the result type and evaluation rule together when composing them.
01What ? does
Which validator failure reaches the café screen?
A café screen receives quantities from a validator, looks up prices and totals table orders. It needs to retain the validator’s reason for refusal, avoid logging successful lookups as missing, and stop a table’s total when a quantity cannot be read.
quantity parses a word with ? into a function that returns OrderError. The program tries “7”, “seven” and an empty word. Predict the second line.
OrderError has a From<ParseIntError> impl; the empty word returns OrderError::Empty directly.
use std::num::ParseIntError;
#[derive(Debug)]
enum OrderError {
Empty,
BadQuantity(ParseIntError),
}
impl From<ParseIntError> for OrderError {
fn from(error: ParseIntError) -> Self {
OrderError::BadQuantity(error)
}
}
fn quantity(word: &str) -> Result<u32, OrderError> {
if word.is_empty() {
return Err(OrderError::Empty);
}
let n: u32 = word.parse()?;
Ok(n)
}
fn main() {
for word in ["7", "seven", ""] {
match quantity(word) {
Ok(n) => println!("{n}"),
Err(error) => println!("{error:?}"),
}
}
}
rustc --edition=2024 main.rs -o main && ./main
Save each experiment as a fresh main.rs and use the guarded edition 2024 command. The exact Debug spelling and numeric failure status in these choices use the declared Unix Rust 1.99.1 profile; the portable main-return rule uses ExitCode::FAILURE.
02Where ? works
Does a missing price have the right return shape?
price looks an item up in a HashMap with get(item)? inside a function that returns Result. Predict what the compiler says.
HashMap::get returns Option<&u32>.
use std::collections::HashMap;
fn price(prices: &HashMap<&str, u32>, item: &str) -> Result<u32, String> {
let found = prices.get(item)?;
Ok(*found)
}
fn main() {
let prices = HashMap::from([("tea", 3)]);
println!("{:?}", price(&prices, "tea"));
}
03main and Err
How does the tool report an Err returned from main?
main returns Result and uses ? for tea, then cake. cake is out of stock. Predict the output and exit status.
main returns Result<(), String>. Interpret the exact status option under the declared Unix profile; separate that status from which stream receives the error and how it is formatted.
fn stock(item: &str) -> Result<u32, String> {
if item == "cake" {
return Err(format!("no {item} left"));
}
Ok(4)
}
fn main() -> Result<(), String> {
println!("tea {}", stock("tea")?);
println!("cake {}", stock("cake")?);
Ok(())
}
04Repair the café orders
Convert with From, log only what is missing, reject the whole order
The café screen needs three repairs: translate both validator failures, run the missing-price log at the right time, and reject an order containing a bad quantity.
The lab file contains its use declarations, the reader, any supplied types and helpers, and a complete main.
Repair the café orders
A From conversion, an eager argument, then a batch that must fail as a whole.
Sources
Sign in to keep your read marks on every device. Sign in
Was this helpful?