Rust Playbook

Course › Week 2 · Errors, collections, traits › Day 3 · lesson 10 of 42 · 20 min reading + 60–90 min practice

Result and the ? operator

Errors are values: return them, pass them up with ?, and keep panic! for bugs.

Result?panic!unwraperror types

On this page
  1. 1. Parsing returns a Result
  2. 2. Returning a Result from your own function
  3. 3. ? passes the error up
  4. 4. ? needs matching error types
  5. 5. main can return a Result
  6. 6. Your own error type
  7. 7. panic or Result?
  8. 8. From Option to Result
  9. Coming from PHP
  10. Practice
  11. Remember

PHP signals failure by throwing an exception, and nothing in a function’s signature tells you it can throw. Rust has no exceptions. A function that can fail says so in its return type, Result<T, E>, and the caller has to deal with it, exactly like Option on Day 5.

You already met Result on Day 6, handled with match. Today: making your own, passing errors up with ?, and the one error type logstat will use.

1. Parsing returns a Result

Result<T, E> is an enum with two variants: Ok(T) holds the value, Err(E) holds the reason. Turning text into a number can fail, so parse returns a Result. The type you want goes on the variable, and parse reads it from there.

src/main.rs
fn main() {
    for input in ["3", "three", "-2"] {
        let parsed: Result<u32, _> = input.parse();
        match parsed {
            Ok(nights) => println!("{input}: {nights} nights"),
            Err(error) => println!("{input}: {error}"),
        }
    }
}
$ cargo run
3: 3 nights
three: invalid digit found in string
-2: invalid digit found in string

_ in Result<u32, _> asks the compiler to fill in the error type itself (it is ParseIntError). Printing an error with {} gives its message, written for people.

In PHP, (int) "three" is silently 0. Here it is an Err, and you cannot get a number out without handling it.

2. Returning a Result from your own function

Return Ok(value) on success and Err(reason) on failure. Here the reason is a String, the simplest error type there is:

src/main.rs
fn parse_nights(input: &str) -> Result<u32, String> {
    let nights: u32 = match input.trim().parse() {
        Ok(n) => n,
        Err(_) => return Err(format!("'{input}' is not a number of nights")),
    };
    if nights == 0 || nights > 365 {
        return Err(format!("{nights} nights is outside 1 to 365"));
    }
    Ok(nights)
}

fn main() {
    for input in ["3", " 14 ", "0", "a week"] {
        match parse_nights(input) {
            Ok(nights) => println!("ok: {nights}"),
            Err(reason) => println!("rejected: {reason}"),
        }
    }
}
$ cargo run
ok: 3
ok: 14
rejected: 0 nights is outside 1 to 365
rejected: 'a week' is not a number of nights

This is a Laravel validation rule written as a function: the signature itself says “gives you a u32 or tells you why not”.

3. ? passes the error up

RuleInside a function that returns a Result, value? means: if it is Err, return that Err right now; otherwise, take what is inside Ok.

It is Day 5’s ? for Option, applied to Result. Each ? is a point where the function may stop, and you can see every one of them. PHP’s exceptions also stop the function, but invisibly, from any line.

src/main.rs
use std::fs;
use std::io;

fn first_line(path: &str) -> Result<String, io::Error> {
    let text = fs::read_to_string(path)?; // a missing file stops here, with its io::Error
    let first = text.lines().next().unwrap_or("");
    Ok(first.to_string())
}

fn main() {
    match first_line("laravel.log") {
        Ok(line) => println!("first line: {line}"),
        Err(error) => println!("cannot read laravel.log: {error}"),
    }
    match first_line("missing.log") {
        Ok(line) => println!("first line: {line}"),
        Err(error) => println!("cannot read missing.log: {error}"),
    }
}
$ cargo run
first line: [2026-11-30 08:00:01] production.INFO: Scheduled command started
cannot read missing.log: No such file or directory (os error 2)

unwrap_or("") takes the value out of an Option, or uses the default you give it when it is None: an empty file has no first line. Unlike unwrap, it can never panic.

fs::read_to_string reads a whole file at once. It is fine here, for one line of a small file; Day 6 of last week explained why logstat streams instead.

4. ? needs matching error types

? returns the error as it is. If the function promises a different error type, it does not compile:

src/main.rsdoes not compile
fn parse_nights(input: &str) -> Result<u32, String> {
    let nights: u32 = input.trim().parse()?;
    Ok(nights)
}

fn main() {
    println!("{:?}", parse_nights("3"));
}
cargo build
error[E0277]: `?` couldn't convert the error to `String`
 --> src/main.rs:2:43
  |
1 | fn parse_nights(input: &str) -> Result<u32, String> {
  |                                 ------------------- expected `String` because of this
2 |     let nights: u32 = input.trim().parse()?;
  |                                    -------^ the trait `From<ParseIntError>` is not implemented for `String`
  |                                    |
  |                                    this can't be annotated with `?` because it has type `Result<_, ParseIntError>`
  |
  = note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
  = help: `String` implements trait `From<T>`:
            From<&String>
            From<&mut str>
            From<&str>
            From<Box<str>>
            From<Cow<'_, str>>
            From<char>

For more information about this error, try `rustc --explain E0277`.
error: could not compile `hello` (bin "hello") due to 1 previous error

The note: says how ? converts errors: through a trait called From. If a conversion from ParseIntError to your error type existed, ? would use it automatically. The Week 2 checkpoint shows how to get one with a single attribute. Until then, convert by hand.

map_err converts the error

map_err turns one error into another before ? passes it on. It takes a closure, the same |…| … inline function you saw with sort_by: here, “given the original error, build this String”.

src/main.rs
fn parse_nights(input: &str) -> Result<u32, String> {
    let nights: u32 = input
        .trim()
        .parse()
        .map_err(|error| format!("'{input}' is not a number of nights: {error}"))?;
    Ok(nights)
}

fn main() {
    println!("{:?}", parse_nights("3"));
    println!("{:?}", parse_nights("three"));
}
$ cargo run
Ok(3)
Err("'three' is not a number of nights: invalid digit found in string")

{:?} shows the variant: Ok(3), Err("…"). Handy while learning; a tool prints the message, never this.

5. main can return a Result

If main returns Result<(), E>, you can use ? in it. When it returns an Err, Rust prints the error and exits with code 1:

src/main.rs
use std::fs;
use std::io;

fn main() -> Result<(), io::Error> {
    let text = fs::read_to_string("missing.log")?;
    println!("{} bytes", text.len());
    Ok(())
}
$ cargo run
Error: Os { code: 2, kind: NotFound, message: "No such file or directory" }
exit code 1

Notice how it prints: the debug form, Os { code: 2, kind: NotFound, … }, which is written for programmers, and no file name. Fine for a quick script. A tool your teammates use handles the error itself and prints a sentence, as logstat does. Ok(()) is “success, with nothing to return”.

6. Your own error type

A String loses information: the caller cannot tell a missing file from a bad line except by reading the text. An enum of errors keeps each case, with the data it needs. This is the shape of logstat’s error type. Tomorrow it gets a standard way to print itself; for now, a method.

src/main.rs
use std::fs::File;
use std::io::{self, BufRead, BufReader};
use std::process;

enum LogError {
    Open { path: String, source: io::Error },
    Read { line: u64, source: io::Error },
}

impl LogError {
    fn message(&self) -> String {
        match self {
            LogError::Open { path, source } => format!("cannot open {path}: {source}"),
            LogError::Read { line, source } => format!("line {line}: {source}"),
        }
    }
}

fn count_lines(path: &str) -> Result<u64, LogError> {
    let file = File::open(path).map_err(|source| LogError::Open {
        path: path.to_string(),
        source,
    })?;

    let mut count: u64 = 0;
    for line in BufReader::new(file).lines() {
        count += 1;
        line.map_err(|source| LogError::Read {
            line: count,
            source,
        })?;
    }
    Ok(count)
}

fn main() {
    match count_lines("storage/logs/laravel.log") {
        Ok(count) => println!("{count} lines"),
        Err(error) => {
            eprintln!("logstat: {}", error.message());
            process::exit(1);
        }
    }
}
$ cargo run
logstat: cannot open storage/logs/laravel.log: No such file or directory (os error 2)
exit code 1

Compare with Day 6: count_lines no longer calls process::exit from deep inside. It returns what went wrong, and only main decides how to report it and which exit code to use. That is what makes the function testable on Day 5.

use std::io::{self, …} imports the module io itself as well as names from inside it. source, alone is the field shorthand from Day 5: the field source gets the variable source.

7. panic or Result?

SituationUseWhy
A file is missing, input is malformed, a server is downResultIt will happen in production; the caller decides what to do
A value that the code itself guarantees, e.g. [0] right after checking the list is not empty[0], or expect("…") with the reasonIf it fails, the program has a bug; stopping is right
Tests and quick experimentsunwrap()A panic is a clear test failure
A tool your team runsNever unwrap() on input or I/OA panic prints a Rust message and exit code 101, not a sentence

expect("why this cannot fail") is unwrap() with a message: if you ever must panic, say why it should have been impossible.

8. From Option to Result

A function that returns a Result cannot use ? on an Option directly, because None carries no reason. ok_or(error) supplies one, then ? works:

src/main.rs
fn level_of(line: &str) -> Result<&str, String> {
    let (head, _message) = line
        .split_once(": ")
        .ok_or(format!("no ': ' in line: {line}"))?;
    let (_env, level) = head
        .rsplit_once('.')
        .ok_or(format!("no level in line: {line}"))?;
    Ok(level)
}

fn main() {
    println!(
        "{:?}",
        level_of("[2026-11-30 09:41:03] production.ERROR: Deadlock")
    );
    println!("{:?}", level_of("#0 {main}"));
}
$ cargo run
Ok("ERROR")
Err("no ': ' in line: #0 {main}")

rsplit_once is split_once from the right: the last . in […] production.ERROR is the one before the level.

Coming from PHP

The same function with exceptions. Everything works, and nothing tells the caller what can go wrong:

count_lines.php
<?php

/** @throws RuntimeException */            // only a comment: nothing checks it
function countLines(string $path): int
{
    $file = new SplFileObject($path);      // throws RuntimeException if missing
    $count = 0;
    foreach ($file as $line) {
        $count++;
    }
    return $count;
}

echo countLines('storage/logs/laravel.log');   // forget the try/catch: a stack trace for the user

In Rust, the possible failure is part of the type, Result<u64, LogError>, and the compiler makes the caller handle it or pass it on with a visible ?. What PHP leaves to discipline and docblocks, Rust checks.

PracticeThe Book ch. 9, Rustlings options and error handling

Read chapter 9 of the Book.

In Rustlings: 12_options 3, then 13_error_handling 1 to 4 (5 and 6 use traits; come back to them after tomorrow).

Exercise: parse a booking row

Rows look like Lina,3,2: guest, nights, guests. Write fn parse_row(row: &str) -> Result<Booking, RowError> with an enum RowError { MissingField(&'static str), BadNumber { field: &'static str, value: String } }. Use split(','), .next() for each field, ok_or and map_err with ?. Print the result for Lina,3,2, Omar,three,2 and Sara,4.

Show the solution
src/main.rs
struct Booking {
    guest: String,
    nights: u32,
    guests: u32,
}

enum RowError {
    MissingField(&'static str),
    BadNumber { field: &'static str, value: String },
}

impl RowError {
    fn message(&self) -> String {
        match self {
            RowError::MissingField(field) => format!("missing {field}"),
            RowError::BadNumber { field, value } => format!("{field} is not a number: '{value}'"),
        }
    }
}

fn number(field: &'static str, value: &str) -> Result<u32, RowError> {
    value.trim().parse().map_err(|_| RowError::BadNumber {
        field,
        value: value.to_string(),
    })
}

fn parse_row(row: &str) -> Result<Booking, RowError> {
    let mut fields = row.split(',');
    let guest = fields.next().ok_or(RowError::MissingField("guest"))?;
    let nights = fields.next().ok_or(RowError::MissingField("nights"))?;
    let guests = fields.next().ok_or(RowError::MissingField("guests"))?;

    Ok(Booking {
        guest: guest.trim().to_string(),
        nights: number("nights", nights)?,
        guests: number("guests", guests)?,
    })
}

fn main() {
    for row in ["Lina,3,2", "Omar,three,2", "Sara,4"] {
        match parse_row(row) {
            Ok(b) => println!("{}: {} nights, {} guests", b.guest, b.nights, b.guests),
            Err(error) => println!("{row}: {}", error.message()),
        }
    }
}
$ cargo run
Lina: 3 nights, 2 guests
Omar,three,2: nights is not a number: 'three'
Sara,4: missing guests

split(',') gives the fields one at a time; each .next() returns the next one as an Option, None when there are no more. That is the iterator idea of Week 3, used in its simplest form.

Remember

  • A function that can fail returns a Result, and ? passes the error up visibly.
  • Low-level functions return errors; only main decides how to report them and with which exit code.
  • unwrap() is for tests; a tool never panics on input or I/O.

Tomorrow: generics and traits. Your error type learns to print itself with {} like every standard error does.