Stderr Diagnostics Leave Stdout For Data
Keep records on stdout and warnings on a locked io::stderr handle so redirection stays clean and diagnostics never corrupt the data stream.
Code
use std::io::{self, Write};
fn main() {
let stderr = io::stderr();
let mut handle = stderr.lock();
println!("record,1");
println!("record,2");
// 数据走 stdout,诊断 diagnostics 走 stderr:重定向互不污染
writeln!(handle, "warn: skipped malformed line").ok();
writeln!(handle, "info: 2 records emitted").ok();
handle.flush().ok();
// 简单场景也可以直接用 eprintln!,批量输出才需要锁定的 handle
}What the snippet does
Read it one way: the function main, doing all the work.
Caveats
- Dependencies number zero; the language runtime covers every call.
Using it
The signature that matters reads fn main()
The file’s steps are announced in the output: record,1, record,2.
Key statements
writeln!(handle, "warn: skipped malformed line").ok();
writeln!(handle, "info: 2 records emitted").ok();
let mut handle = stderr.lock();
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 does Stderr Diagnostics Leave Stdout For Data print when run?
- The script runs standalone; its 2 labeled outputs include `record,1`, `record,2`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.