当我们想要多次使用特定的Result类型该怎么办呢?回忆一下Rust的内容,它可以让我们建立别名。因此我们可以为特定Result定义一个别名。
在模块级别,建立别名是特别有帮助的。在特定模块中出现的错误通常有相同的错误类型,因此一个别名可以简洁的定义所有的相关Result。它是如此有用,以致于标准库都提供了一个:io::Result。
下面示例展示了这种语法:
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 main() {
print(multiply("10", "2"));
print(multiply("t", "2"));
}