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.
Code
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 ownmatch.
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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.