Exit Codes From Main With ExitCode

Return std::process::ExitCode from main so the process exit status reflects the outcome, with custom non-zero codes for script and CI checks.

RustCli Tooling

Code

rustsnippet
30 lines
use std::process::ExitCode;

// 返回 ExitCode 让 main 的退出码由业务结果决定,而不是永远 0
fn run(argv: &[String]) -> Result<(), String> {
    if argv.len() < 2 {
        return Err("usage: deploy <env>".to_string());
    }
    let env = &argv[1];
    if env != "staging" && env != "prod" {
        return Err(format!("unknown env {env}"));
    }
    println!("deploying to {env}");
    Ok(())
}

fn main() -> ExitCode {
    let argv: Vec<String> = std::env::args().collect();

    match run(&argv) {
        Ok(()) => {
            println!("done");
            ExitCode::SUCCESS
        }
        Err(reason) => {
            eprintln!("error: {reason}");
            // 自定义退出码:脚本与 CI 用非零码判断失败
            ExitCode::from(2)
        }
    }
}

How the snippet works

Exit Codes From Main With ExitCode is built around the functions run and main.

Fallible operations return Result, forcing the caller to handle both arms explicitly. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

What to watch for

  • Errors travel through Result; if you drop the ? operators while adapting, each call site needs its own match.

Applying it

Entry signature: fn run(argv: &[String]) -> Result<(), String>

The demo output is labeled (deploying to, done), so every printed line maps back to its originating operation.

There are 1 call inside main — run — executed top to bottom.

Statements that matter

return Err("usage: deploy <env>".to_string());
return Err(format!("unknown env {env}"));
Err(reason) => {
    eprintln!("error: {reason}");
    // 自定义退出码:脚本与 CI 用非零码判断失败
    ExitCode::from(2)
}

Interactive Tools for This Topic

FAQ

What happens when a call fails?
Through `Result` values. Nothing panics inside the snippet; the caller decides how to handle each failure.
What does Exit Codes From Main With ExitCode print when run?
No setup needed: run the file and look for labeled lines like `deploying to`, `done` in the output.