error-concept
Propagate and convert errors with From
The question-mark operator on Result returns early on failure and converts the error into the enclosing Result error type when the applicable From implementation exists. The successful value continues through the function. Expected stdout (not executed): Ok(12) invalid inventory quantity Common mistake: Expecting question mark to automatically convert any error type.
Formal Syntax & Structure
rust syntaxrust
impl From<ParseIntError> for LoadError; fn read_qty(s: &str) -> Result<u32, LoadError>Working Example
Example Snippetrust
use std::{error::Error, fmt, num::ParseIntError};#[derive(Debug)]struct LoadError(ParseIntError);impl fmt::Display for LoadError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "invalid inventory quantity") }}impl Error for LoadError { fn source(&self) -> Option<&(dyn Error + 'static)> { Some(&self.0) }}impl From<ParseIntError> for LoadError { fn from(e: ParseIntError) -> Self { Self(e) }}fn read_qty(s: &str) -> Result<u32, LoadError> { Ok(s.parse::<u32>()?) }fn main() { println!("{:?}", read_qty("12")); println!("{}", read_qty("bad").unwrap_err());}