`main` returning `Result` idiom

โš“ Rust    ๐Ÿ“… 2026-03-29    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 8      

surdeus

I've noticed the Rust documentation, the Rust book, and other resources are very fond of mentioning that main can return Result. Yes, it can return any type that implements the Termination trait.

As far as I understand it, Result in return exists to make code snippets simpler, mostly for docs and related areas, along with some sort of design consistency choice.

Only from this perspective does it make sense that Result's implementation of the Termination trait is to debug print the error object. A quick search shows this has been the subject of several discussions on this forum alone, e.g., 1 2 3 .

The posts effectively consist of the poster having written,

fn main() -> Result<(), Box<dyn Error>> {
    let str = read_to_string("file.txt")?;
    println!("{str}");
    Ok(())
}

and they are bothered by the format of the output during errors.

These forum topics are somewhat silly to read, as they consist of a mix of people harassing the original poster for not just doing basic error handling in main and other people posting their own boilerplate code they use in every program to solve this micro-problem:

  1. Make main always call a separate run or program or _main function and then abort on error or return ExitCode (normal)
  2. Return your own error type in main and make its fmt method just print the message rather than the expected fmt behaviour (weird, but commonly suggested)
  3. Create your own Termination type

So what is the problem? Needing a couple lines of code to display something in a reasonable format is not a problem. What could be a problem is faulty idioms and documentation. The reason it is a problem in this case is only because we are talking about the most basic possible program you could possibly write.

The aforementioned discussion post examples often use abort() and then go "oh, wait." abort() might not release resources and the docs say you should avoid using the function when you can use regular control flow and return an ExitCode,

Ok, now let's look at the docs for ExitCode::FAILURE. You'll see the following notice:

If youโ€™re only returning this and SUCCESS from main, consider instead returning Err(_) and Ok(()) respectively, which will return the same codes (but will also eprintln! the error).

Wait a minute, didn't we all just agree returning Result in main is essentially just for examples? We know this is a serious language and we want the language to take itself seriously too.

P.S. I will of course make a PR to change at least that last piece of documentation unless other's totally disagree with me on this subject

3 posts - 3 participants

Read full topic

๐Ÿท๏ธ Rust_feed