Loading
0x60Lesson 7 of 17

Write functions and handle errors with Result

Use typed function signatures and explicit error handling.

18 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.

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. Matching on Result is a clear beginner-friendly pattern.

Try it

Up to 15 XP

Result flow from helper to caller

Follow how Result propagates from a helper function into caller behavior.

Message 1 of 3Predicted 0/0
Caller
divide helper
Match 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 Rust.

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…