Between Option and Result in Rust
The two conversions worth memorising: ok_or adds an error, ok drops one.
fn first_word(line: &str) -> Result<&str, &'static str> {
line.split_whitespace().next().ok_or("empty line")
}
fn main() {
println!("{:?}", first_word("hello there"));
println!("{:?}", first_word(" "));
let parsed: Option<i32> = "12".parse().ok();
println!("{:?}", parsed);
let nested: Result<Option<i32>, std::num::ParseIntError> =
Some("5").map(|s| s.parse()).transpose();
println!("{:?}", nested);
}
How it works
ok_orturnsNoneinto anErryou choose.okthrows the error away and keeps aOption.transposeswaps a nested Option and Result.
Keywords and builtins used here
OptionResultSomefirst_wordfni32letmainstaticstr
The run, in numbers
- Lines
- 15
- Characters to type
- 407
- Tokens
- 148
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 93 seconds.
Step 3 of 3 in Option, step 3 of 15 in Error handling.