Result propagation and the ? operator
Handle fallible steps clearly with `Result` and `?`.
- Use
?to propagate parsing and validation errors.
The ? operator short-circuits on Err and unwraps Ok values, making fallible code concise. It works in functions that return Result (or compatible types) and keeps error flow explicit.
1fn parse_positive(value: &str) -> Result<i32, String> {
2 let number: i32 = value.trim().parse().map_err(|_| "invalid integer".to_string())?;
3 if number > 0 { Ok(number) } else { Err("must be positive".to_string()) }
4}
5
6fn main() {
7 println!("{:?}", parse_positive("12"));
8}Ok(12)
Use ? for each fallible step to return early on failure. This keeps the happy path readable while preserving explicit error handling.
Try it
Up to 15 XPTrace `?` through a fallible workflow
Follow how ? either continues with Ok or returns early with Err.
Key takeaways
Use
?to propagate parsing and validation errors.Rust uses types and ownership rules to prevent common bugs.
Small experiments build intuition quickly.
Lesson quiz
5 questions · pass with 4 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write Rust
These run for real. Write the program, press Run tests, and read what the compiler tells you - learning to read compiler messages is half of learning Rust.
Divide with propagated errors
Implement safe_divide returning Result<i32, String>. Return an error for division by zero; otherwise return quotient. Print value or error.
- Valid division
- Division by zero
Rust lessons are authored for modern stable Rust; exercises run on Rust 1.82 via Wandbox, a free public service. Your source code and test input are sent to that service.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…