capypad
0 day streak
rust / intermediate
Snippet

Error Propagation with the ? Operator

The '?' operator is a concise way to handle errors. If a Result is an Err, it returns early from the function with that error; otherwise, it unwraps the Ok value.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
use std::fs::File;
use std::io::{self, Read};
 
fn read_username() -> Result<String, io::Error> {
let mut f = File::open("hello.txt")?;
let mut s = String::new();
f.read_to_string(&mut s)?;
Ok(s)
}
Breakdown
1
File::open("hello.txt")?
Attempts to open a file. If it fails, the error is returned immediately.
2
Ok(s)
Wraps the successful result in an Ok variant.