Sub topic 13
Returning Result from main
This chapter assumes you know the ? operator, Box<dyn Error>, and how Debug and Display differ. It shows how main can return a Result, so ? works at the top of your program.
Why main can return a Result
Without a return type, main cannot use ?, because ? needs a function that returns Result or Option. You would have to match every error by hand. Rust allows main to return any type that implements the Termination trait. The standard library implements it for these types:
(), which means exit code 0.Result<T, E>, whereTis itselfTerminationandEimplementsDebug.std::process::ExitCode, which lets you pick the exit code.
A first example
use std::num::ParseIntError;
fn main() -> Result<(), ParseIntError> {
let port: u16 = "8080".parse()?;
println!("port = {port}");
let bad: u16 = "abc".parse()?;
println!("never printed: {bad}");
Ok(())
}The first line prints port = 8080. The second ? sees an Err and returns it from main. The runtime then writes Error: ParseIntError { kind: InvalidDigit } to standard error and exits with status 1.
Mixing error types
A function that returns Result<(), Box<dyn Error>> accepts any error type through ?, because each one converts into the box with From. This is the usual choice for small programs and scripts.
use std::error::Error;
use std::fs;
fn main() -> Result<(), Box<dyn Error>> {
let text = fs::read_to_string("config.txt")?;
let port: u16 = text.trim().parse()?;
println!("port = {port}");
Ok(())
}The two ? lines produce different error types, io::Error and ParseIntError. Both fit the one return type. If config.txt does not exist, you see Error: Os { code: 2, kind: NotFound, message: "No such file or directory" }.
The output uses Debug, not Display
The runtime formats the error with {:?}. A custom error with a polished Display message still prints as its derived Debug form, such as Error: Missing("port"). That is fine for developers and rough for end users.
Controlling the exit code and message
For user-facing tools, keep main small and call a run function. Print the error yourself with Display and return an ExitCode.
use std::num::ParseIntError;
use std::process::ExitCode;
fn run() -> Result<(), ParseIntError> {
let n: i32 = "x".parse()?;
println!("{n}");
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 and exits with status 2.
Common mistakes
- Using
?in a plainfn main(). The compiler rejects it because()is not aResult. - Returning an error type that does not implement
Debug. Add#[derive(Debug)]. - Expecting
Displayoutput. The runtime always usesDebug. - Returning
Ok(())early by accident and skipping cleanup you meant to run.
Exercise
A program has fn main() -> Result<(), ConfigError>. ConfigError implements both Display (message "missing key: port") and a derived Debug. The program returns Err(ConfigError::Missing("port")). What appears on stderr, and what is the exit code?
Show answer
stderr shows Error: Missing("port"), the Debug form, not the Display message. The exit code is 1. To show the Display message or choose another code, call a run function from main, print with eprintln!("{e}"), and return an ExitCode.