Sub topic 11
Returning Result from main
This chapter assumes you know how ? propagates errors, how the From trait converts error types, and how Box<dyn Error> works as a catch-all. Here you will put those pieces together at the top of a program.
Why main can return Result
Up to now, ? has only worked inside helper functions. If you used it in a plain fn main(), the compiler would reject it, because main returns () and ? needs a return type that can hold an error.
Rust lets main return a Result. The usual signature is:
fn main() -> Result<(), Box<dyn std::error::Error>>The success type is () because a program has no value to hand back. The error type is Box<dyn Error>, so one main can use ? on io::Error, ParseIntError, and any other type that implements Error. Each one converts through From into the box.
A complete example
use std::error::Error;
use std::fs;
fn main() -> Result<(), Box<dyn Error>> {
let text = fs::read_to_string("count.txt")?;
let count: u32 = text.trim().parse()?;
println!("count = {count}");
Ok(())
}Two different errors can occur here. read_to_string returns io::Error if the file is missing. parse returns ParseIntError if the text is not a number. Both use ?, and both end up as Box<dyn Error>.
Try three runs:
- Without
count.txt, the program prints an error and stops. - With
count.txtcontainingabc, you get a parse error. - With
count.txtcontaining42, it printscount = 42.
What happens when main returns Err
When main returns Err(e), the runtime does two things:
- It prints
Error:followed by theDebugform ofeto standard error. - It exits the process with a failure status, which is code 1 on most platforms.
If main returns Ok(()), the exit status is 0.
Which error type to use
You can use any error type in main as long as it implements Debug. The type must be usable as a termination value. In practice, you have two choices.
| Choice | Good for | Trade-off |
|---|---|---|
| `Box<dyn Error>` | Small programs, scripts, examples | The concrete type is erased, so callers cannot match on variants |
| Your own error enum | Programs where you want control over the message | You write the `Display`, `Error`, and `From` code |
A custom enum works in main too, as long as it derives Debug. If you want a readable message, though, the derived Debug output may look rough. A common fix is to keep main small, call a run function that returns your error, and print the Display text yourself.
Controlling the output and exit code
This version prints the friendly message and picks the exit code:
use std::error::Error;
use std::fs;
use std::process;
fn run() -> Result<u32, Box<dyn Error>> {
let text = fs::read_to_string("count.txt")?;
let count = text.trim().parse::<u32>()?;
Ok(count)
}
fn main() {
match run() {
Ok(count) => println!("count = {count}"),
Err(e) => {
eprintln!("error: {e}");
process::exit(2);
}
}
}Here main returns (), so no ? appears in it. The run function holds the logic and can use ? freely. The {e} formatting uses Display, so the output reads error: invalid digit found in string instead of a debug dump.
How the pieces connect
Summary of rules
maincan returnResult<(), E>whenE: Debug.Errfrommainprints theDebugform and exits with a failure status.Box<dyn Error>is the easiest choice forE.- For polished messages or specific exit codes, move the logic into
runand handle the result inmain.
Exercise
A program has fn main() -> Result<(), MyError> where MyError derives Debug and has a hand-written Display that says "could not read config". When main returns Err, which text appears on standard error, the Display text or the Debug text, and what is the exit status?
Show answer
The Debug text appears, prefixed with Error: , for example Error: ConfigMissing. The Display text is not used. The exit status is a failure status, normally 1. To show the Display text, call a run function from main, match on its result, and print with eprintln!("{e}").
Exercise
Why does fn main() { let n: i32 = "5".parse()?; } fail to compile, and what is the smallest change that fixes it?
Show answer
? needs the enclosing function to return Result (or Option), but main returns (). Change the signature to fn main() -> Result<(), Box<dyn std::error::Error>> and add Ok(()) as the last expression.