🎯 As mentioned in intro exercise 9, Python uses exceptions; in Rust we model failures as data with Result<T, E>.
Defining a custom error enum keeps error handling explicit and type-safe.
In this bite you’ll create a small evaluator that parses "a / b" and performs checked division.
You'll also use enums from intro exercise 8 again, this time to represent possible errors. Defining a custom error enum keeps error handling explicit and type-safe because the compiler forces you to handle all possible error cases (unlike exceptions in Python which can be silently ignored).
✅ Your task
- Define an error enum:
#[derive(Debug, PartialEq, Eq)]
pub enum CalcError {
DivisionByZero,
ParseInt(String), // carries the offending token
BadFormat, // when the input isn't "a / b"
}
- Implement:
-
parse_int(tok: &str) -> Result<i32, CalcError>Trim and parse; on failure returnCalcError::ParseInt(tok.to_string()). -
safe_div(a: i32, b: i32) -> Result<i32, CalcError>ReturnErr(CalcError::DivisionByZero)ifb == 0, elseOk(a / b). -
eval_div(expr: &str) -> Result<i32, CalcError>Accept strings like"12 / 3"(allow spaces). Split on'/', parse both sides withparse_int, then divide withsafe_div. Any shape other than exactly two parts isBadFormat.
💡 Hints
- Use
split('/')andcollect::<Vec<_>>()orsplit_once('/'). - Use
map_errto convert parse errors. - Return early with
?to keep code minimal and readable.
Example tests:
use CalcError::*;
assert_eq!(eval_div("12/3"), Ok(4));
assert_eq!(eval_div(" 10 / 2 "), Ok(5));
assert_eq!(eval_div("7/0"), Err(DivisionByZero));
assert_eq!(eval_div("x/3"), Err(ParseInt("x".into())));
assert_eq!(eval_div("1/2/3"), Err(BadFormat));