From d5cae8ff597ab85d817d3abb6f30159f1823a0f2 Mon Sep 17 00:00:00 2001 From: Antoine Dupuis Date: Wed, 13 Nov 2024 23:51:09 +0100 Subject: [PATCH] Add alternative solution using From trait --- solutions/13_error_handling/errors6.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/solutions/13_error_handling/errors6.rs b/solutions/13_error_handling/errors6.rs index 8679361..7bad200 100644 --- a/solutions/13_error_handling/errors6.rs +++ b/solutions/13_error_handling/errors6.rs @@ -29,6 +29,21 @@ impl ParsePosNonzeroError { } } +/// As an alternative solution, implementing the `From` trait allows for the +/// automatic conversion from a `ParseIntError` into a `ParsePosNonzeroError` +/// using the `?` operator, without the need to call `map_err`. +/// +/// ``` +/// let x: i64 = s.parse()?; +/// ``` +/// +/// Traits like `From` will be dealt with in later exercises. +impl From for ParsePosNonzeroError { + fn from(err: ParseIntError) -> Self { + ParsePosNonzeroError::ParseInt(err) + } +} + #[derive(PartialEq, Debug)] struct PositiveNonzeroInteger(u64);