Skip to main content

How to Use the Question Mark (?) Operator in Rust

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

Rust's ? operator unwraps a Result inside a function that returns one. On Ok you get the value; on Err the function returns that error to its caller at once. It does the work of a whole match in one character.

Syntax​

Syntax
fn <name>(<parameters>) -> Result<T, E> {
let <value> = <expression>?;
Ok(<result>)
}
PartWhat it does
<expression>?If <expression> is Ok(v), the whole thing is v. If it's Err(e), the function returns Err with that error.
-> Result<T, E>? on a Result only works in a function that returns a Result (or another type that accepts it).
EThe function's error type. The error ? meets is converted into it with From.

The Rust Reference on the try propagation expression "uses the value of the inner expression and the Try trait to decide whether to produce a value, and if so, what value to produce, or whether to return a value to the caller, and if so, what value to return." For a Result, "Result::Ok(val) evaluates to val" and "Result::Err(e) returns Result::Err(From::from(e))". It adds: "The try propagation operator is sometimes called the question mark operator, the ? operator, or the try operator."

The Example​

The example's double function reads a number from text and doubles it. parse can fail, so double passes its error on with ? instead of handling it.

Prerequisites​

  • Rust, installed with rustup, which comes with Cargo. This guide uses Rust 1.100.0.

Step 1: Create a Project​

Terminal
cargo new demo
cd demo
Output
Creating binary (application) `demo` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

cargo new demo creates a folder named demo with a Cargo.toml file, which describes the project, and src/main.rs, which holds the code. cd demo moves into it.

Step 2: Write the Code​

Replace the contents of src/main.rs with:

src/main.rs, where double takes text, parses it into an i32 with the question mark operator and returns Ok of twice the number, and main prints double("21") and double("forty").

src/main.rs
use std::num::ParseIntError;

fn double(text: &str) -> Result<i32, ParseIntError> {
let n: i32 = text.parse()?;
Ok(n * 2)
}

fn main() {
println!("{:?}", double("21"));
println!("{:?}", double("forty"));
}

text.parse() returns Result<i32, ParseIntError>. The ? after it either gives n the number or returns the ParseIntError from double, which is why double declares that error type.

Step 3: Run It​

Terminal
cargo run -q
Output
Ok(42)
Err(ParseIntError { kind: InvalidDigit })

A zsh terminal where cargo run -q prints Ok(42) and then Err(ParseIntError with kind InvalidDigit).

cargo run compiles the program and runs it, and -q hides Cargo's own status lines. "21" parsed, so double reached Ok(n * 2). "forty" didn't, so ? returned the parse error and the multiplication never ran.

Return Your Own Error with map_err​

? converts the error only when the function's error type knows how to be made from it. A String doesn't, so this function stops the build:

src/main.rs
fn double(text: &str) -> Result<i32, String> {
let n: i32 = text.parse()?;
Ok(n * 2)
}
Output
error[E0277]: `?` couldn't convert the error to `String`

map_err turns the error into a String first, so ? has nothing left to convert:

src/main.rs
fn double(text: &str) -> Result<i32, String> {
let n: i32 = text.parse().map_err(|e| format!("bad number: {e}"))?;
Ok(n * 2)
}
Output
Err("bad number: invalid digit found in string")

Use ? on an Option​

In a function that returns an Option, ? works on an Option the same way: Some(v) gives v, and None returns None.

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

fn main() {
println!("{:?}", first_char_upper("ada"));
println!("{:?}", first_char_upper(""));
}
Output
Some('A')
None

Common Mistakes​

MistakeWhat happensDo this instead
Using ? in a function that returns nothing, such as a plain fn main()error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)Give the function a Result return type, or handle the error with match
An error type that the ? error can't convert intoerror[E0277]: `?` couldn't convert the error to `String` Convert it first with map_err
Forgetting Ok(…) around the final valueerror[E0308]: mismatched typesEnd with Ok(value)

Troubleshooting​

SymptomLikely causeFix
cannot use the `?` operator in a function that returns `()` ? in a function without a Result return typeChange the return type; the compiler's help shows one
the trait `From<ParseIntError>` is not implemented for `String` The error types don't matchUse map_err, or return the original error type

FAQ​

Can I use ? in main?​

Yes, when main returns a Result, such as fn main() -> Result<(), ParseIntError>. When main returns an Err, Rust prints Error: and the error, and the program exits with code 1.

Is ? the same as unwrap?​

No. unwrap stops the whole program on an Err. ? hands the error to the caller, which can still handle it.

Conclusion​

Put ? after an expression that returns a Result to keep the Ok value and return any Err from the function at once. Use map_err when the function's error type differs, and ? on an Option in functions that return one.

Additional Resources​