Rust-Programming-Cookbook/Chapter06/sample_aliases_result.rs

29 wiersze
786 B
Rust

//-- #########################
//-- Task: Implementing mapt for Result
//-- Author: Vigneshwer.D
//-- Version: 1.0.0
//-- Date: 26 March 17
//-- #########################
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 double_number(number_str: &str) -> AliasedResult<i32> {
number_str.parse::<i32>().map(|n| 2 * n)
}
// 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 main() {
print(double_number("10"));
print(double_number("t"));
}