Error handling
Typed errors
A String as the error type is enough to get started, but the caller can do nothing with it except print it. An error enum lets the caller react differently to each case with a match, and tests can check exactly which error occurs.
use std::fmt; #[derive(Debug, PartialEq)]enum ParseError { WrongFieldCount { expected: usize, found: usize }, InvalidNumber { field: &'static str, value: String },} impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { ParseError::WrongFieldCount { expected, found } => { write!(f, "{expected} champs attendus, {found} trouvés") } ParseError::InvalidNumber { field, value } => { write!(f, "champ {field} : '{value}' n'est pas un nombre") } } }} impl std::error::Error for ParseError {} fn parse_strike(line: &str) -> Result<f64, ParseError> { let fields: Vec<&str> = line.split(',').collect(); if fields.len() != 2 { return Err(ParseError::WrongFieldCount { expected: 2, found: fields.len() }); } fields[1].trim().parse().map_err(|_| ParseError::InvalidNumber { field: "strike", value: fields[1].trim().to_string(), })} fn main() { for line in ["T1,100", "T2", "T3,abc"] { match parse_strike(line) { Ok(strike) => println!("{line} -> {strike}"), Err(e) => println!("{line} -> erreur : {e}"), } }}Two impl blocks to remember. fmt::Display defines the readable message printed by {}. std::error::Error officially declares the type as an error, which makes it compatible with Box<dyn Error> and the ecosystem. These are trait implementations: the next module explains the mechanism in detail.
Your turn
Add a NegativeQuantity(f64) variant to the enum, its message in Display, and have parse_quantity return it when the quantity is negative.
use std::fmt; #[derive(Debug)]enum ParseError { InvalidNumber(String),} impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { ParseError::InvalidNumber(value) => write!(f, "'{value}' n'est pas un nombre"), } }} fn parse_quantity(text: &str) -> Result<f64, ParseError> { let quantity: f64 = text .trim() .parse() .map_err(|_| ParseError::InvalidNumber(text.to_string()))?; Ok(quantity)} fn main() { for input in ["10", "-3", "x"] { match parse_quantity(input) { Ok(q) => println!("{q}"), Err(e) => println!("erreur : {e}"), } }}Once the variant is added, the compiler flags the Display match that does not cover it: let it guide you.
use std::fmt; #[derive(Debug)]enum ParseError { InvalidNumber(String), NegativeQuantity(f64),} impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { ParseError::InvalidNumber(value) => write!(f, "'{value}' n'est pas un nombre"), ParseError::NegativeQuantity(q) => write!(f, "quantité négative : {q}"), } }} fn parse_quantity(text: &str) -> Result<f64, ParseError> { let quantity: f64 = text .trim() .parse() .map_err(|_| ParseError::InvalidNumber(text.to_string()))?; if quantity < 0.0 { return Err(ParseError::NegativeQuantity(quantity)); } Ok(quantity)} fn main() { for input in ["10", "-3", "x"] { match parse_quantity(input) { Ok(q) => println!("{q}"), Err(e) => println!("erreur : {e}"), } }}This is match exhaustiveness serving errors: you cannot forget the message of a new variant. The early return Err(...) is the idiomatic form for a check in the middle of a function.