aliases for Result

How about when we want to reuse a specific Result type many times?
Recall that Rust allows us to create aliases. Conveniently,
we can define one for the specific Result in question.

At a module level, creating aliases can be particularly helpful. Errors
found in a specific module often have the same Err type, so a single alias
can succinctly define all associated Results. This is so useful that the
std library even supplies one: io::Result!

Here’s a quick example to show off the syntax:

  1. use std::num::ParseIntError;
  2. // Define a generic alias for a `Result` with the error type `ParseIntError`.
  3. type AliasedResult<T> = Result<T, ParseIntError>;
  4. // Use the above alias to refer to our specific `Result` type.
  5. fn multiply(first_number_str: &str, second_number_str: &str) -> AliasedResult<i32> {
  6. first_number_str.parse::<i32>().and_then(|first_number| {
  7. second_number_str.parse::<i32>().map(|second_number| first_number * second_number)
  8. })
  9. }
  10. // Here, the alias again allows us to save some space.
  11. fn print(result: AliasedResult<i32>) {
  12. match result {
  13. Ok(n) => println!("n is {}", n),
  14. Err(e) => println!("Error: {}", e),
  15. }
  16. }
  17. fn main() {
  18. print(multiply("10", "2"));
  19. print(multiply("t", "2"));
  20. }

See also:

io::Result