What does the question mark operator (?) mean in Rust and how does it work?
Hello everyone! I recently started learning Rust and came across a strange operator — the question mark (?). I saw it in someone else's code but can't understand what it does.
Here's an example I found:
```rust
use std::fs::File;
use std::io::Read;
fn read_file(path: &str) -> Result {
let mut file = File::open(path)?; // What does `?` do here?
let mut contents = String::new();
file.read_to_string(&mut contents)?; // And here?
Ok(contents)
}
```
I tried writing similar code without this operator using `match`, and it turned out very verbose:
```rust
fn read_file_verbose(path: &str) -> Result {
let mut file = match File::open(path) {
Ok(f) => f,
Err(e) => return Err(e),
};
let mut
No answers yet.
Log in to leave an answer