Rust Reference ยท Core Traits
The Termination trait
Reference for std::process::Termination in Rust: which types main can return, how Result and ExitCode become exit codes, and how to implement it yourself.
std::process::Termination is the trait that decides what happens when main returns. The runtime calls report() on the value main returns and uses the ExitCode it gives back as the process exit status. That is why fn main() can return (), a Result, or an ExitCode: all of them implement the trait.
Most programs never mention the trait by name. You meet it when you write fn main() -> Result<(), Box<dyn Error>> so that ? works in main, or when you want a specific exit code. You can also implement it for your own type to centralise how a program reports success and failure.
pub trait Termination { fn report(self) -> ExitCode; }
Try 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.
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.
Syntax
pub trait Termination { fn report(self) -> ExitCode; }
| Name | Description |
|---|---|
self |
The value main returned. It is consumed. |
Returns: the ExitCode the process should end with.
The standard library implements Termination for:
| Type | Result |
|---|---|
() |
ExitCode::SUCCESS (exit code 0) |
! and Infallible |
never returns a value (these cannot be constructed) |
ExitCode |
itself |
Result<T, E> where T: Termination, E: Debug |
on Ok(t) it reports t; on Err(e) it prints Error: {e:?} to standard error and gives ExitCode::FAILURE (exit code 1) |
Usage notes
- The error is printed with
Debug, notDisplay. ABox<dyn Error>from a parse failure prints something likeError: ParseIntError { kind: InvalidDigit }. If you want friendlier text, catch the error inmain, print it with{}, and return anExitCode. - Exit codes are a byte.
ExitCode::from(u8)is the only constructor for arbitrary codes. Operating systems keep just 8 bits, so 256 would look like 0 on Unix. reportis called aftermainreturns, so local values inmainhave already been dropped. Destructors run before the code is reported. This is different fromstd::process::exit, which ends the process immediately without unwinding the stack.- A panic in
maindoes not go throughTermination. A panic exits with code 101 on the standard runtime. Seepanic!. - Only the value returned from
mainis reported. The same trait lets a#[test]function return aResult: the test harness usesreport()to decide whether the test passed. - Stable since Rust 1.61 (when
mainwas allowed to returnExitCodeand the trait was stabilised).