rust-ape-example/src/bin/error_result_result_alias.rs
2022-09-07 10:49:49 +05:30

33 lines
826 B
Rust

// ./src/error/result/result_alias.md
use std::num::ParseIntError;
// Define a generic alias for a `Result` with the error type `ParseIntError`.
type AliasedResult<T> = Result<T, ParseIntError>;
// Use the above alias to refer to our specific `Result` type.
fn multiply(first_number_str: &str, second_number_str: &str) -> AliasedResult<i32> {
first_number_str.parse::<i32>().and_then(|first_number| {
second_number_str.parse::<i32>().map(|second_number| first_number * second_number)
})
}
// Here, the alias again allows us to save some space.
fn print(result: AliasedResult<i32>) {
match result {
Ok(n) => println!("n is {}", n),
Err(e) => println!("Error: {}", e),
}
}
fn part0() {
print(multiply("10", "2"));
print(multiply("t", "2"));
}
pub fn main() {
part0();
}