Loading
0x40Lesson 5 of 6

Write functions and handle errors with Result

Use typed function signatures and explicit error handling.

15 min 5-question quiz 1 code exercise
By the end of this lesson you can
  • Define reusable functions and return Result for 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.

main.rs
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}
Output
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 Result for 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.

Exercise 1

Convert minutes to seconds

+25 XP

Write to_seconds(minutes: i32) -> i32 and print the result for one input value.

  • Two minutes
  • Zero minutes
main.rs
Loading editor…

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…

Did you like the lesson? 😆👍
Consider a donation to support our work: