? sign at end of function

I have the following code in rust:

let mut client_options =
    ClientOptions::parse("mongodb://localhost:27017")?;

What does mean ? at end of parse() ?

See here: "The question mark operator": Operator expressions - The Rust Reference

Basically the ? unwraps the Result returned by parse(). If the Result is Ok processing continues. It the Result is an Error the function returns immediately with that Result as the functions return value.

This does require that the function this line of code is in returns a Result type.

1 Like

To be precise, anything that implements the Try trait.

1 Like

Here's the relevant section in The Book: https://doc.rust-lang.org/stable/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator

1 Like