Skip to main content

How to Return a Result from main in Rust

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

Rust's main can return a Result. Then the ? operator works in main too, and when main returns an error, Rust prints it and exits with code 1, so scripts and CI see the failure.

Syntax​

Syntax
fn main() -> Result<(), <ErrorType>> {
// statements that can use ?
Ok(())
}
PartWhat it does
Result<(), <ErrorType>>main returns nothing useful on success, (), or an error of <ErrorType>.
?Inside main, returns the error from main when an expression fails.
Ok(())The last expression: everything worked.

The Rust Book: "When a main function returns a Result<(), E>, the executable will exit with a value of 0 if main returns Ok(()) and will exit with a nonzero value if main returns an Err value." The Rust Reference allows any return type that implements the Termination trait, "A trait for implementing arbitrary return types in the main function."

The Example​

The example parses two pieces of text into numbers with ?: "42", which works, and "forty-two", which makes main return the error.

Prerequisites​

  • Rust, installed with rustup, which comes with Cargo. This guide uses Rust 1.100.0.

Step 1: Create a Project​

Terminal
cargo new demo
cd demo
Output
Creating binary (application) `demo` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

cargo new demo creates a folder named demo with a Cargo.toml file, which describes the project, and src/main.rs, which holds the code. cd demo moves into it.

Step 2: Write the Code​

Replace the contents of src/main.rs with:

src/main.rs, where main returns Result of unit and ParseIntError, parses "42" with the question mark operator and prints it, then parses "forty-two" the same way, and ends with Ok(()).

src/main.rs
use std::num::ParseIntError;

fn main() -> Result<(), ParseIntError> {
let n: i32 = "42".parse()?;
println!("Parsed {n}");

let m: i32 = "forty-two".parse()?;
println!("Parsed {m}");
Ok(())
}

parse returns a Result with a ParseIntError on failure, so that's the error type main declares.

Step 3: Run It and Check the Exit Code​

Run the program, then print the exit code of the last command:

Terminal
cargo run -q
echo $?

A zsh terminal where cargo run -q prints Parsed 42 and Error: ParseIntError with kind InvalidDigit, and echo $? prints 1.

Output
Parsed 42
Error: ParseIntError { kind: InvalidDigit }
1

cargo run compiles the program and runs it, and -q hides Cargo's own status lines. The first parse worked. The second failed, so ? returned the error from main, and Rust printed Error: with the error in its debug format, on standard error, and exited with code 1. Parsed for the second number never printed.

Mixed Error Types with Box<dyn Error>​

When main calls things that fail with different error types, declare Box<dyn Error>, which accepts any of them:

src/main.rs
use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {
let n: i32 = "42".parse()?;
println!("Parsed {n}");
let m: f64 = "x".parse()?;
println!("Parsed {m}");
Ok(())
}
Output
Parsed 42
Error: ParseFloatError { kind: Invalid }

The first ? met a ParseIntError type, the second a ParseFloatError, and both fit. This program exited with code 1 as well.

A String Error Prints in Quotes​

The error is printed with its debug format, so a String error keeps its quotes:

src/main.rs
fn main() -> Result<(), String> {
Err(String::from("config file is missing"))
}
Output
Error: "config file is missing"

Common Mistakes​

MistakeWhat happensDo this instead
Forgetting Ok(()) at the enderror[E0308]: mismatched types: expected `Result<(), ParseIntError>`, found `()` End main with Ok(())
Using ? in a main without a return typeerror[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` …Add the return type; the compiler's help suggests Result<(), Box<dyn std::error::Error>>
Expecting a friendly messageRust prints the error's debug format, such as ParseIntError { kind: InvalidDigit }Print your own message with eprintln! and return an ExitCode when users see it

Troubleshooting​

SymptomLikely causeFix
implicitly returns `()` as its body has no tail or `return` expressionNo Ok(()) at the endAdd it
Exit code 1 with an Error: linemain returned an ErrRead the error after Error:

FAQ​

What exit code does main give on Ok(())?​

0, as the Rust Book's quote above says.

Why not unwrap everything in main?​

unwrap turns an error into a panic, exit code 101, with a message about a thread and a source line. Returning the error gives a shorter Error: line and exit code 1.

Conclusion​

Declare fn main() -> Result<(), E>, use ? freely, and end with Ok(()). An error then reaches the shell as an Error: line on standard error and exit code 1. Use Box<dyn Error> when several error types meet in main.

Additional Resources​