Result Handling
Level: intro (score: 1)
🎯 Python has try/except
, but Rust takes a different path with Result
.
Instead of throwing exceptions, Rust encourages you to return a Result<T, E> where:
- T is the type you return on success (Ok)
- E is the type you return on failure (Err)
This forces you to explicitly handle success and failure cases, making your code safer and more predictable.
✅ Your task:
Implement the divide
function which:
- Takes two integers
a
andb
- Returns
Ok(a / b)
ifb
is not zero - Returns an
Err(String)
with the message"division by zero"
ifb
is zero
This exercise introduces:
- The Result enum (Ok and Err variants)
- Using generics in Result<T, E>
- Defensive programming in Rust
🧠 Remember: in Rust, not handling an error is a compile-time error — it’s part of the language’s safety guarantees.