Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 132 ยท Getting Started

The main Function, Arguments and Exit Codes

Learn how Rust programs start and end - fn main, returning Result or ExitCode, process::exit, env::args, exit status 101 for panics and how Termination works.

Every Rust executable starts in a function named main. When main returns, the program ends, and the operating system receives a small number called the exit code (or exit status). Shell scripts, build tools, CI servers and other programs use that number to decide whether your program worked: 0 means success, anything else means failure.

So far every main in this tutorial looked like fn main() { ... } and returned nothing. That is only one of several shapes. This lesson shows the others, how a program reads its command-line arguments, three different ways to stop early, and what Rust does when something goes wrong. You will meet Result properly in Result and the ? operator in The ? Operator; here we only need the basic idea that Result<(), E> means "finished, or failed with an error of type E".

The simplest main

The smallest valid program is a function called main with no parameters and no return value:

Rust
fn main() {}

It takes no arguments, because Rust gives command-line arguments through a function you call (std::env::args), not through parameters like C's argc and argv. It is not pub, it is not async, and it must be in the root of the crate. Returning nothing means "the unit type ()", and a normal return gives exit code 0.

What can main return? The rule is: any type that implements the trait std::process::Termination. The standard library implements it for (), ! (the never type), Result<T, E> (with conditions), and ExitCode. Anything else is rejected at compile time:

Rust main cannot return an i32 (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

If you come from C, this is the surprise: the real message is error[E0277]: mainhas invalid return typei32, with the note maincan only return types that implementTermination``. The exit code is chosen by a type that knows how to report itself, not by a bare integer.

Command-line arguments

std::env::args() returns an iterator over the arguments as Strings. The first item is always the name or path the program was started with; the real arguments follow. Because it is an iterator, you can collect it, skip the first item, or take just the one you want:

Rust Reading arguments with a default

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

In our online editor you cannot type arguments, so the program sees only the program name: number of items: 1, no argument lines, and the default Hello, world!. On your own computer, ./hello Ferris would count 2 items and greet Ferris. (With Cargo you pass them after two dashes: cargo run -- Ferris, because arguments before -- belong to Cargo itself.)

Two details matter in real programs:

  • args() panics if an argument is not valid Unicode. Use std::env::args_os() when you need to accept any file name, which yields OsString values.
  • Do not trust args[0]. It is whatever the caller wrote, and it can even be empty. Never use it for security decisions or to locate files.

For anything with flags such as --verbose and --output file, hand-written parsing becomes tedious fast. Most real tools use the clap crate, which is outside what our single-file editor can run; the idea is shown in Crates and Dependencies.

main returning a Result

Most programs do things that can fail: opening a file, parsing text, connecting to a server. If main could return a Result, you could use ? right inside it instead of nesting match expressions. It can:

Rust main returns Result and prints the error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The first line prints n = 12. The second ? sees an Err, returns it from main, and the runtime does two things: it prints Error: ParseIntError { kind: InvalidDigit } to standard error, and it exits with code 1. The println! for m never runs. The editor shows exit code 1 under the output.

Note the format. The runtime prints the error with the Debug format ({:?}), not the friendly Display format. That is acceptable for a developer, but ugly for a user. You get a tidier result with a custom error type or by handling the error yourself, which is the next example.

When main can fail in several different ways you can use Result<(), Box<dyn Error>>, where Box<dyn Error> means "any error". The ? operator converts any standard error into it automatically:

Rust Box of dyn Error as the error type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

You wrote a nicely worded Display message (missing key port), yet the runtime prints Error: ConfigError { key: "port" }, the derived Debug form. If you want the friendly message, do not return the error from main. Handle it where you can print it, as shown in the next section. Writing your own error types is the topic of Custom Error Types.

ExitCode: choose the number yourself

std::process::ExitCode lets main pick the exit status explicitly. You get two constants, ExitCode::SUCCESS (0) and ExitCode::FAILURE (1), and ExitCode::from(n) for any u8 value. Different numbers can tell a script what went wrong:

Rust Returning ExitCode

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The program prints one line to standard output, one line to standard error with eprintln! (errors and diagnostics belong there, so that they do not pollute data you pipe elsewhere), and exits with status 3. The number is a u8 because operating systems only keep the low 8 bits on most platforms; 256 would look like 0.

A tidy structure used by many command-line tools is to put the real work in a function that returns a Result, and let main translate it into a message and an exit code. That gives you the friendly Display output and total control:

Rust run returns Result, main reports it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Because the editor passes no arguments, run fails at ok_or and the program prints error: no arguments given and exits with 1. The function run knows nothing about the process, so you can test it with ordinary function calls; that is a design benefit beyond tidiness. Testing shows how.

process::exit: stop right now

std::process::exit(code) terminates the program immediately from anywhere, with any i32 code. Its return type is !, the never type, which tells the compiler that nothing after the call can run. That means it fits into any expression, for example as the else branch of a match that otherwise yields a value.

The catch is what it skips. exit does not unwind the stack, so destructors (Drop) of live values never run, buffered output in your own BufWriter may be lost, and temporary files are not deleted:

Rust exit skips destructors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

You see before exit and nothing else: dropped is never printed. Replace the exit call with a plain return and dropped appears, because leaving main normally drops its local variables first. For this reason, prefer returning an ExitCode from main and keep process::exit for rare cases deep inside code where you truly must quit, such as a fatal error in a library-free helper or after a child process was forked.

Panics and exit code 101

A panic is Rust's way of stopping when the program reaches a state it cannot continue from: an out-of-bounds index, an unwrap on None, a failed assert!, a division by zero, an integer overflow in a debug build. It prints a message and, by default, unwinds the stack, running destructors on the way out. If the panic reaches the top of main, the process exits with code 101:

Rust A panic unwinds and exits with 101

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The standard error shows a message of the form thread 'main' (2) panicked at main.rs:11:21: followed by index out of bounds: the len is 0 but the index is 0. The location is file:line:column, which is the first thing to read when debugging. On standard output you can see dropped, because unwinding ran the destructor. The number 101 is only a convention of the Rust runtime, but it is handy: a script can tell a Rust panic (101) from an error you deliberately reported with ExitCode (usually 1 or another small number).

Compare the two kinds of failure, because choosing between them is a core Rust skill:

Panic Error returned as Result
Meaning A bug, or a broken promise An expected problem (missing file, bad input)
Handled by Usually nobody; the program stops The caller decides
Exit code 101 Whatever you choose, 1 by default from main
Example v[10] on a 3-item vector "abc".parse::<i32>()

The rule of thumb: user mistakes and environment problems are Results; programmer mistakes are panics. Panics goes much deeper, including RUST_BACKTRACE and catch_unwind.

You can ask Cargo to make panics abort immediately instead of unwinding with panic = "abort" in Cargo.toml. Then destructors do not run and the process ends by signal (on Linux typically exit status 134). It makes binaries smaller and is common in embedded work.

Under the hood: the Termination trait

Everything main can return works through one small trait:

Rust
// shape of the trait in std::process (simplified)
pub trait Termination {
    fn report(self) -> ExitCode;
}

The runtime calls your main, then calls .report() on its return value and uses the resulting ExitCode. For () it gives SUCCESS; for Result<T, E> it gives SUCCESS on Ok and, on Err, prints Error: {:?} to stderr and gives FAILURE. Because it is a normal trait, you can implement it for your own type:

Rust A custom type that decides the exit code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

With the preset input x the program prints the warning and exits with 10. Change the Input box to ok and it exits silently with 0. Custom Termination types are rare, but they show that there is no magic: main is an ordinary function whose return value the runtime inspects.

Common mistakes

  • Returning a number from main (-> i32) as in C. Use ExitCode instead.
  • Using unwrap everywhere so every small problem becomes a panic with exit code 101 and an unfriendly message. Return a Result instead.
  • Printing errors with println!. Send errors to standard error with eprintln!.
  • Calling process::exit while values still need cleanup, which skips Drop.
  • Expecting friendly text from a main that returns Err. The runtime prints the Debug form.
  • Indexing args[1] without checking. Use args().nth(1) or check the length first.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What exit code does a Rust program that panics in main normally return?

    An uncaught panic that unwinds out of main ends the process with status 101. A main that returns Err gives 1 instead.
  2. 2. Which return type is NOT allowed for main?

    main must return a type that implements Termination. i32 does not, so rustc reports E0277: main has invalid return type.
  3. 3. What happens to the destructors (Drop) of local variables when you call std::process::exit(1)?

    process::exit ends the process immediately. Nothing is unwound, so Drop implementations do not run. Returning from main drops the locals normally.
  4. 4. A main that returns Err(e) prints the error to stderr. Which format does it use?

    The runtime prints Error: followed by the Debug form of the error and exits with code 1. For a friendly message, handle the error yourself and print it with Display.
  5. 5. What does env::args().nth(1) give you when no argument was passed?

    Item 0 is the program name, item 1 is the first real argument. nth returns Option<String>, so a missing argument is None.

Summary

  • Execution starts at fn main; leaving it ends the program, and the return value decides the exit code.
  • main may return (), Result<(), E> (where E: Debug), ExitCode, or any type implementing Termination; a bare integer is a compile error.
  • std::env::args() is an iterator whose first item is the program name; args_os() accepts non-Unicode arguments.
  • An Err returned from main prints Error: {:?} to stderr and exits with 1; ExitCode::from(n) gives you full control.
  • A common structure is fn run() -> Result<..> plus a main that prints the error with eprintln! and returns an ExitCode.
  • process::exit stops immediately without running destructors; a panic unwinds (running destructors) and exits with 101.
  • Use errors for expected failures and panics for bugs.

Next: Variables and Mutability starts the next chapter and shows how let, mut and shadowing work.