Pybites Logo Rust Platform

Error Result

Level: intro (score: 1)

🚀 These intro exercises are prep for our Rust Intro Cohort Program.

🎯 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

  1. 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"
}
 
  1. Implement:
  • parse_int(tok: &str) -> Result<i32, CalcError> Trim and parse; on failure return CalcError::ParseInt(tok.to_string()).

  • safe_div(a: i32, b: i32) -> Result<i32, CalcError> Return Err(CalcError::DivisionByZero) if b == 0, else Ok(a / b).

  • eval_div(expr: &str) -> Result<i32, CalcError> Accept strings like "12 / 3" (allow spaces). Split on '/', parse both sides with parse_int, then divide with safe_div. Any shape other than exactly two parts is BadFormat.


💡 Hints

  • Use split('/') and collect::<Vec<_>>() or split_once('/').
  • Use map_err to 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));