Write functions and handle errors with Result
Use typed function signatures and explicit error handling.
- Define reusable functions and return
Resultfor fallible operations.
Rust functions declare parameter and return types explicitly. For operations that can fail, Rust uses Result<T, E> instead of exceptions. Pattern matching or combinators handle success (Ok) and failure (Err) explicitly.
1fn divide(a: i32, b: i32) -> Result<i32, String> {
2 if b == 0 {
3 Err("division by zero".to_string())
4 } else {
5 Ok(a / b)
6 }
7}
8
9fn main() {
10 println!("{:?}", divide(12, 3));
11}Ok(4)
Explicit error handling makes control flow visible in code and avoids hidden exception paths. For beginner programs, matching on Result is a clear way to understand every branch.
Key takeaways
Define reusable functions and return
Resultfor fallible operations.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 C.
Convert minutes to seconds
Write to_seconds(minutes: i32) -> i32 and print the result for one input value.
- Two minutes
- Zero minutes
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…