mirror of
https://github.com/ahgamut/rust-ape-example.git
synced 2024-05-28 16:28:08 +00:00
d976dc883b
via panflute and https://github.com/rust-lang/rust-by-example
51 lines
1.2 KiB
Rust
51 lines
1.2 KiB
Rust
// ./src/error/multiple_error_types/option_result.md
|
|
|
|
|
|
use std::num::ParseIntError;
|
|
|
|
fn double_first(vec: Vec<&str>) -> Option<Result<i32, ParseIntError>> {
|
|
vec.first().map(|first| {
|
|
first.parse::<i32>().map(|n| 2 * n)
|
|
})
|
|
}
|
|
|
|
fn part0() {
|
|
let numbers = vec!["42", "93", "18"];
|
|
let empty = vec![];
|
|
let strings = vec!["tofu", "93", "18"];
|
|
|
|
println!("The first doubled is {:?}", double_first(numbers));
|
|
|
|
println!("The first doubled is {:?}", double_first(empty));
|
|
// Error 1: the input vector is empty
|
|
|
|
println!("The first doubled is {:?}", double_first(strings));
|
|
// Error 2: the element doesn't parse to a number
|
|
}
|
|
|
|
use std::num::ParseIntError;
|
|
|
|
fn double_first(vec: Vec<&str>) -> Result<Option<i32>, ParseIntError> {
|
|
let opt = vec.first().map(|first| {
|
|
first.parse::<i32>().map(|n| 2 * n)
|
|
});
|
|
|
|
opt.map_or(Ok(None), |r| r.map(Some))
|
|
}
|
|
|
|
fn part1() {
|
|
let numbers = vec!["42", "93", "18"];
|
|
let empty = vec![];
|
|
let strings = vec!["tofu", "93", "18"];
|
|
|
|
println!("The first doubled is {:?}", double_first(numbers));
|
|
println!("The first doubled is {:?}", double_first(empty));
|
|
println!("The first doubled is {:?}", double_first(strings));
|
|
}
|
|
|
|
pub fn main() {
|
|
part0();
|
|
part1();
|
|
}
|
|
|