Rust Question Mark Operator

Functions that call other fallible functions often repeat the same pattern: check the result, return early on failure, keep going on success. The question mark operator compresses that pattern into a single character. Picture a relay race: if any runner drops the baton, the whole team stops at once and reports the problem.

The Long Way

The function below reads a username from a file. Each step needs a match.

use std::fs::File;
use std::io::{self, Read};

fn read_username() -> Result<String, io::Error> {
    let mut file = match File::open("user.txt") {
        Ok(f) => f,
        Err(e) => return Err(e),
    };

    let mut name = String::new();
    match file.read_to_string(&mut name) {
        Ok(_) => Ok(name),
        Err(e) => Err(e),
    }
}

The Short Way

Placing ? after a Result expression does the same work. On Ok, the operator unwraps the value. On Err, the operator returns the error from the current function immediately.

fn read_username() -> Result<String, io::Error> {
    let mut file = File::open("user.txt")?;
    let mut name = String::new();
    file.read_to_string(&mut name)?;
    Ok(name)
}
 File::open ----Ok----> continue ----Ok----> Ok(name)
     |                      |
    Err                    Err
     |                      |
     +-----> return Err(e) from function

Chaining Calls

Question marks combine with method chains to shrink code further.

fn read_username() -> Result<String, io::Error> {
    let mut name = String::new();
    File::open("user.txt")?.read_to_string(&mut name)?;
    Ok(name)
}

The standard library offers std::fs::read_to_string, which performs both steps in one call.

fn read_username() -> Result<String, io::Error> {
    std::fs::read_to_string("user.txt")
}

Where the Operator Works

The operator only works inside functions whose return type can carry an error. A function returning () rejects it.

fn main() {
    // let n: i32 = "5".parse()?;   // error: main returns ()
}

The fix is to let main return a Result.

use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {
    let n: i32 = "5".parse()?;
    println!("Number: {n}");
    Ok(())
}

The type Box<dyn Error> accepts any error type, so a single function can use ? on parse errors, file errors, and more.

Automatic Error Conversion

The operator calls From::from on the error before returning it. The conversion lets different error types fit one return type. Your own types join the system by implementing the From trait.

 ParseIntError --?-->  From  -->  Box<dyn Error>
 io::Error     --?-->  From  -->  Box<dyn Error>

Using ? with Option

Functions that return Option accept the operator too. A None exits the function with None.

fn first_char_upper(text: &str) -> Option<char> {
    let c = text.chars().next()?;
    Some(c.to_ascii_uppercase())
}

fn main() {
    println!("{:?}", first_char_upper("rust"));  // Some('R')
    println!("{:?}", first_char_upper(""));      // None
}

A single function cannot mix both kinds. Convert with ok_or or ok() when the types differ.

A Complete Example

The program below reads two numbers from text and adds them.

use std::num::ParseIntError;

fn add_texts(a: &str, b: &str) -> Result<i32, ParseIntError> {
    let x: i32 = a.trim().parse()?;
    let y: i32 = b.trim().parse()?;
    Ok(x + y)
}

fn main() {
    println!("{:?}", add_texts("4", " 6 "));
    println!("{:?}", add_texts("4", "six"));
}
Ok(10)
Err(ParseIntError { kind: InvalidDigit })

Common Mistakes

  • Using ? inside a function that returns nothing
  • Mixing Option and Result in one function without converting
  • Forgetting the final Ok(...) wrapper
  • Placing a semicolon after the last expression and returning unit by accident

Practical Benefits

The operator keeps the main path of a function visible. A reader sees the intended steps in order, with no clutter from repeated error checks. Error handling remains in place, yet it no longer dominates the screen.

Callers keep control. The function passes the error upward, so the calling code decides whether to retry, show a message, or stop. Low-level functions rarely know the right reaction.

Practice Ideas

  • Write a function that reads a file and parses its first line as a number, using ? for both steps.
  • Change main to return Result and propagate an error to the terminal.
  • Use ? with Option to fetch the first word of a sentence.

Common Mistakes

Adding a semicolon after the final Ok(value) line changes the return value to unit and triggers a type error. Leave the semicolon off the last expression.

Reading Code with Question Marks

Each question mark marks a spot where the function may leave early. Scan a function for them to count the possible exit points. A function with four question marks has four places where an error can escape, and each deserves a test.

Key Points

  • The ? operator unwraps Ok or returns the error immediately.
  • The enclosing function must return a compatible Result or Option.
  • Box<dyn Error> lets one function handle many error kinds.
  • The operator converts errors through the From trait.