Pybites Logo Rust Platform

Fibonacci Sequence

Medium +3 pts

🎯 Python 3.10 introduced structural pattern matching with match/case. Rust has had match from the start — and it's one of the language's most powerful features.

match in Rust

Where Python uses if/elif chains or match/case, Rust uses match expressions:

match n {
    0 => println!("zero"),
    1 => println!("one"),
    _ => println!("something else"),  // _ is the catch-all (like Python's case _)
}

Two things make Rust's match stand out:

  1. It's exhaustive — you must handle every possible case. Forget a variant? Compiler error. This prevents bugs that if/elif chains silently allow.
  2. It's an expressionmatch returns a value, so you can use it on the right side of let or as a function's return:
let label = match n {
    0 => "zero",
    1 => "one",
    _ => "other",
};

Match guards

You can add conditions to match arms with if:

match n {
    x if x < 0 => println!("negative"),
    0 => println!("zero"),
    _ => println!("positive"),
}

The x if x < 0 is a match guard — it binds the value to x and only matches if the condition is true.

panic! — Rust's "raise Exception"

When something goes truly wrong, Rust has panic!:

panic!("something went horribly wrong: {}", details);

This immediately terminates the current thread with an error message — similar to Python's raise Exception(...). In production Rust code, you'd usually prefer returning a Result (we'll cover that in later exercises), but panic! is appropriate when a function receives input that should never happen.

In tests, you can assert that code panics:

#[test]
#[should_panic]
fn test_negative_input() {
    my_function(-1);  // this test passes if my_function panics
}

Login to see the full task and start coding.

This is a premium exercise

Log in to unlock the full exercise and start coding.

Login to access this exercise