Error handling
The ? operator
Most of the time, a function does not know what to do with an error and has to pass it up to the caller. The ? placed after a Result does exactly that: if it is an Ok, it extracts the value; if it is an Err, it leaves the function right away, returning that error.
use std::num::ParseFloatError; fn notional(quantity: &str, price: &str) -> Result<f64, ParseFloatError> { let q: f64 = quantity.trim().parse()?; let p: f64 = price.trim().parse()?; Ok(q * p)} fn main() { println!("{:?}", notional("100", "151.5")); // Ok(15150.0) println!("{:?}", notional("100", "n/a")); // Err(...)}?, you would need two nested match expressions. ? only works inside a function that itself returns a Result (or an Option).Often the errors of the functions you call do not have the same type as yours. map_err converts the error before propagating it: a chance to add context (which field, which value).
fn parse_field(name: &str, value: &str) -> Result<f64, String> { value .trim() .parse::<f64>() .map_err(|_| format!("champ {name} : '{value}' n'est pas un nombre"))} fn trade_value(fields: &[&str]) -> Result<f64, String> { let strike = parse_field("strike", fields[0])?; let quantity = parse_field("quantity", fields[1])?; Ok(strike * quantity)} fn main() { println!("{:?}", trade_value(&["100", "50"])); println!("{:?}", trade_value(&["100", "cinquante"]));}|_| ... is a closure that ignores the original error: we replace it with a clearer message. Closures get their own module later on.Your turn
Use ? to write average_price, which parses a list of textual prices and returns their average, or the first error encountered.
use std::num::ParseFloatError; fn average_price(prices: &[&str]) -> Result<f64, ParseFloatError> { todo!()} fn main() { println!("{:?}", average_price(&["100", "102", "104"])); // Ok(102.0) println!("{:?}", average_price(&["100", "oops", "104"])); // Err(...)}A plain for loop; the ? inside the loop leaves the function at the first invalid price.
use std::num::ParseFloatError; fn average_price(prices: &[&str]) -> Result<f64, ParseFloatError> { let mut total = 0.0; for text in prices { let price: f64 = text.trim().parse()?; total += price; } Ok(total / prices.len() as f64)} fn main() { println!("{:?}", average_price(&["100", "102", "104"])); // Ok(102.0) println!("{:?}", average_price(&["100", "oops", "104"])); // Err(...)}The final value is wrapped in Ok(...): the function returns a Result, not an f64. Forgetting that Ok is the most common early mistake.