Option, Result and the ? operator in Rust

Learn Rust · Beginner · 12 min · After Structs, enums and match in Rust

How does Rust handle a value that may be missing or an operation that may fail?

  1. 1Guess

    fn main() {
        for text in ["42", "x"] {
            match text.parse::<i32>() {
                Ok(n) => println!("number {n}"),
                Err(_) => println!("not a number"),
            }
        }
    }
    
    What does this program print?
  2. 2Read

    No null, no exceptions

    Rust has no null and no exceptions. A value that may be missing is an Option<T>: Some(value) or None. An operation that may fail returns a Result<T, E>: Ok(value) or Err(error). Both are ordinary enums, so match works on them. The compiler makes you handle both cases before you can use the value inside.

  3. 3Code

    Working with Option

    1 / 2
    fn first_word(text: &str) -> Option<&str> {
        text.split_whitespace().next()
    }
    
    fn main() {
        if let Some(word) = first_word("hello brave world") {
            println!("first word: {word}");
        }
        let empty = first_word("   ");
        println!("{}", empty.unwrap_or("nothing"));
        let length = first_word("rust").map(|w| w.len());
        println!("{length:?}");
    }
    

    Read the program. What will it print?

    Run it in the playground

  4. 4Read

    The ? operator

    Inside a function that returns Result, ? after a call does two things. On Ok(v) it gives you v. On Err(e) it returns that error from your function at once. In a function that returns Option, it returns None the same way. unwrap and expect panic on the bad case instead. They are fine for experiments, not for real programs.

  5. 5Code

    Passing errors up with ?

    1 / 2
    use std::num::ParseIntError;
    
    fn total(a: &str, b: &str) -> Result<i32, ParseIntError> {
        let x = a.parse::<i32>()?;
        let y = b.parse::<i32>()?;
        Ok(x + y)
    }
    
    fn main() {
        println!("{:?}", total("20", "22"));
        match total("20", "abc") {
            Ok(sum) => println!("sum {sum}"),
            Err(e) => println!("error: {e}"),
        }
    }
    

    Read the program. What will it print?

    Run it in the playground

  6. 6Fix

    fn main() {
        let n: i32 = "42".parse()?;
        println!("{n}");
    }
    
    This program does not compile. What is the bug?
  7. 7Say it back

  8. 8Mission · 10 min

    Write a program with a list of two &str values. Parse both as numbers with ?, and print their sum or the error. Try "7" and "8", then "7" and "x".

    cargo new parse-sum
    cd parse-sum
    cargo run

Common questions

What is the difference between Option and Result in Rust?
Option<T> is for a value that may be missing: it is Some(value) or None. Result<T, E> is for an operation that may fail: it is Ok(value) or Err(error). Use Option when absence is normal and needs no reason, and Result when you want to say what went wrong.
What does the ? operator do in Rust?
The ? operator goes after an expression that returns a Result or an Option. If it holds a good value, you get that value. If it holds an error or None, the function returns early with it. So the function must itself return a compatible Result or Option, or the code does not compile.
When should I use unwrap in Rust?
unwrap and expect return the value, but they panic and stop the program on Err or None. They are fine in quick experiments, in tests, and when you can prove the value is there. In real code, prefer match, if let, unwrap_or or the ? operator, so bad input is handled instead of crashing the program.

Sources

Measured with rustc 1.100.1 (play.rust-lang.org, stable, edition 2024) on 2026-12-03

Published Dec 3, 2026 · Updated Dec 3, 2026

Never miss new offers and news

New tools, credits, and AI news are added regularly. Pick how you want to hear about them.

Telegram channel

Join @aifree_dev and get new free AI offers and news right in your Telegram feed.

Browser notifications

Turn on push notifications and get an alert on this device whenever something new is posted. No account needed.

Email newsletter

A weekly digest of new, changed and expiring free AI offers. Double opt-in, one-click unsubscribe. See the latest issue.

Unsubscribe anytime. Privacy

Frequently asked questions

What is aifree.dev?

aifree.dev helps everyone access AI through a curated directory of free AI tools, API credits, free tiers, and startup programs for coding, image, voice, video, and students - verified regularly.

How are offers presented?

Each offer includes its access details, free models when available, and expiration information when provided. Limited-time deals stay visible so they are easy to compare.

Do education and startup programs need verification?

Yes. Providers usually ask students to verify their status with a school email, student ID, or a program like the GitHub Student Pack, and ask startups to verify company details such as age, funding, or website. Check each offer’s claim page for the exact requirements.

What kinds of free AI offers are listed?

Free tiers and free trials from AI providers, free API credits, startup and student programs, and free tools for coding, image generation, voice, and video.

How can I suggest a tool or report a broken link?

Use the submit form: paste the offer page URL and a short note. A person checks every submission before anything is listed. Broken links and changed terms go through the same form.

Know a good one?

Tell us about an AI tool worth knowing. Found a broken link? We want to hear that too.

Submit an offer