Return a Result Type from the Main Function in Rust
Rust
The main()
function in a Rust programme can return a Result
type, which allows you to provide feedback to users as well as setting the appropriate exit codes for the programme.
Example
use std::num::ParseIntError;
fn main() -> Result<(), ParseIntError> {
let number_str = "this can't be parsed as a number";
let number = match number_str.parse::<i32>() {
Ok(number) => number,
Err(e) => return Err(e),
};
println!("{}", number);
Ok(())
}
The above programme prints Error: ParseIntError { kind: InvalidDigit }
to stdout.
When the parse::<i32>()
method returns an error:
- The
match
expression enters theErr()
branch - The error is passed into the branch
- Finally another
Err()
is returned - the error is output tostderr
and the function (and therefore the programme) is terminated.
Note that in Linux the exit status of running this programme is 1, denoting that the command did not complete successfully.
Here’s another example:
/**
* Contrived function, returns an error if the values are the same.
**/
fn get_largest(a: u32, b: u32) -> Result<u32, &'static str> {
if a == b {
return Err("equal values");
}
if a > b { Ok(a) } else { Ok(b) }
}
fn main() -> Result<(), &'static str> {
let a = 42;
let b = 42;
let number = match get_largest(a, b) {
Ok(number) => number,
Err(e) => return Err(e),
};
// If no error, use `number`.
println!("{}", number);
Ok(())
}
comments powered by Disqus