Sub topic 13
Returning Result from main
This chapter assumes you know ? and the Result type. It covers what main is allowed to return, what the runtime prints when main returns an Err, and how to control the exit code.
Why main can return a Result
? returns early from the enclosing function when it sees an Err. If main returns (), you can't use ? in it, and you end up writing match or unwrap at the top of the program. Rust lets main return a Result so that ? works there too.
use std::num::ParseIntError;
fn main() -> Result<(), ParseIntError> {
let port: u16 = "8080".parse()?;
println!("port {port}");
let bad: u16 = "abc".parse()?;
println!("never reached {bad}");
Ok(())
}Running this prints port 8080 to standard output. The second ? hits an Err and returns from main. The program then writes this to standard error and exits with status 1:
Error: ParseIntError { kind: InvalidDigit }The last line of main is Ok(()). Without it the function would return () and not match the declared type.
What the runtime does with the return value
The return type of main must implement the std::process::Termination trait. The runtime calls main, passes the value to Termination::report, and uses the result as the process exit code.
The standard library implements Termination for these types:
| Return type of `main` | Behavior |
|---|---|
| `()` | Exit code 0. |
| `Result<(), E>` where `E: Debug` | Exit code 0 on `Ok`. On `Err`, prints `Error: {:?}` to stderr and exits with 1. |
| `ExitCode` | Exits with the code you choose. |
| `Result<ExitCode, E>` where `E: Debug` | Like `Result<(), E>`, but a successful run picks its own code. |
| `!` (never returns) | Allowed, for programs that loop forever or call `process::exit`. |
The bound is E: Debug, not E: Display. The error is printed through its Debug implementation, and Display is never used.
The Debug output is not user friendly
Because the runtime uses Debug, the message is the one the derive macro generates. Here is the main from the earlier custom error example, which returns Result<(), ConfigError>:
use std::fmt;
use std::num::ParseIntError;
#[derive(Debug)]
enum ConfigError {
Missing(&'static str),
BadNumber(ParseIntError),
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ConfigError::Missing(key) => write!(f, "missing key: {key}"),
ConfigError::BadNumber(e) => write!(f, "bad number: {e}"),
}
}
}
impl std::error::Error for ConfigError {}
fn read_port(value: Option<&str>) -> Result<u16, ConfigError> {
let text = value.ok_or(ConfigError::Missing("port"))?;
text.parse::<u16>().map_err(ConfigError::BadNumber)
}
fn main() -> Result<(), ConfigError> {
println!("{}", read_port(Some("8080"))?);
println!("{}", read_port(None)?);
Ok(())
}The program prints 8080, then fails with this on stderr:
Error: Missing("port")The Display text "missing key: port" that you wrote never appears. This is fine for quick tools and examples. For a program that real users run, it is usually the wrong output.
Box<dyn Error> in main
Result<(), Box<dyn Error>> is a common return type for main. Any error type that implements Error converts into Box<dyn Error> through From, so ? accepts all of them.
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
let port: u16 = "8080".parse()?;
println!("port {port}");
let n: i32 = "12x".parse()?;
println!("n = {n}");
Ok(())
}Box<dyn Error> forwards Debug to the error inside it. This program therefore still prints Error: ParseIntError { kind: InvalidDigit }.
You can also build a boxed error from a string with .into():
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
let args: Vec<String> = std::env::args().collect();
if args.len() < 2 {
return Err("usage: tool <file>".into());
}
println!("file: {}", args[1]);
Ok(())
}The string becomes a private error type inside the box. Its Debug output is the quoted string, so a run with no arguments prints Error: "usage: tool <file>". The quotes are noise that users will notice.
Printing a readable message with ExitCode
A common pattern is to move the real logic into a run function and make main a thin wrapper. main returns std::process::ExitCode. It prints the error with Display and picks the exit code itself.
use std::error::Error;
use std::process::ExitCode;
fn run() -> Result<(), Box<dyn Error>> {
let port: u16 = "80x".parse()?;
println!("port {port}");
Ok(())
}
fn main() -> ExitCode {
match run() {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("error: {e}");
ExitCode::from(2)
}
}
}This prints error: invalid digit found in string to stderr and exits with status 2. Points to note:
ExitCode::SUCCESSis 0 andExitCode::FAILUREis 1.ExitCode::fromtakes au8. Operating systems keep only the low 8 bits of a status, so a larger number can't be expressed.eprintln!writes to stderr, which keeps error messages out of output that other programs may pipe or parse.runis an ordinary function. You can call it from tests and check itsResultdirectly, which you can't do withmain.
To report a source chain, walk Error::source in the Err branch and print each cause. Plain {e} shows only the outermost message.
Choosing a style
- Use
Result<(), Box<dyn Error>>for scripts, examples, and prototypes. It is the least code, and aDebugmessage is acceptable. - Use
Result<(), YourError>when you want a precise error type and the derivedDebugoutput is readable enough. A hand-writtenDebugimplementation can improve the text. - Use an
ExitCodewrapper when the program has real users. You get aDisplaymessage, a deliberate exit code, and a testablerun.
Common mistakes
- Forgetting
Ok(()). The compiler reports a mismatched type, because the last statement ends in;and produces(). - Using
?in amainthat returns(). The error says that?can only be used in a function that returnsResultorOption. Change the signature. - Returning an error type without
Debug. The compiler rejects it becauseTerminationrequiresE: Debug. Add#[derive(Debug)]. - Expecting
Displayoutput. If you seeMissing("port")and wantedmissing key: port, switch to theExitCodepattern. - Expecting destructors to run in every case. A
mainthat returns normally drops its locals first, so cleanup runs. A call tostd::process::exitskips destructors, so avoid it when cleanup matters. Returning anExitCodeis the safer alternative.
Exercise
What does this program print to stderr, and what is its exit status? use std::error::Error; fn main() -> Result<(), Box<dyn Error>> { let n: i32 = "".parse()?; println!("{n}"); Ok(()) }
Show answer
It prints Error: ParseIntError { kind: Empty } to stderr and exits with status 1. An empty string parses to the Empty kind of ParseIntError. The ? converts it to Box<dyn Error>, main returns the Err, and the runtime prints it with Debug and exits with 1. Nothing is printed to stdout because println! is never reached.
Exercise
Rewrite the main above so that a failure prints error: cannot read number: <Display text of the error> to stderr and exits with status 3. Which return type do you use for main?
Show answer
Move the logic into run and make main return ExitCode:
use std::error::Error;
use std::process::ExitCode;
fn run() -> Result<(), Box<dyn Error>> {
let n: i32 = "".parse()?;
println!("{n}");
Ok(())
}
fn main() -> ExitCode {
match run() {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("error: cannot read number: {e}");
ExitCode::from(3)
}
}
}