rust-ape-example/src/bin/error_multiple_error_types_option_result.rs
2022-09-07 11:36:05 +05:30

41 lines
1 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
}
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();
}