What does the '?' operator do?


#1

I’ve seen it in Rust code several times but I can’t seem to find any clear documentation for what it does. I tried the RFC, but I can’t understand it :frowning: Can someone give a simpler explanation?


#2

It unwraps the value and provides an early return on Err or None values.

It is explained in the Rust book


#3

To expand on Christiaan676’s answer, the following line:

let foo = my_function()?;

is equivalent to the following:

let foo = match my_function() {
    OK(v) => v,
    Err(err) => return Err(err.into()),
};

It has been introduced into the language because this pattern of “if the result is Ok, unwrap its value, otherwise, just get out of the function” is so very common. Shortening this match block into a single character makes error handling much easier:

let variable = function()?.chained_method()?.another_method()?;

Two additional notes:

  • Because the expansion of the ? operator contains a return Err(...), you can only use it in a function which returns some sort of Result.
  • The .into() call in the expansion comes from the Into trait. It basically allows automatic conversion from one error type into another. Because of this, it is possible to return many different errors from a function and still use the ? operator.

PS: Just as I finished writing this, Christiaan676 has added the link to the Rust book, which also explains all this. Oh well. :slight_smile:


#4

Thanks @Christiaan676 and @troiganto! I get it now :smile:


#5

Note also that ? works with Option as well in a similar manner.


#6

For future reference: https://doc.rust-lang.org/book/first-edition/syntax-index.html


#7

If you’re interested in the internal details: