Writing to Standard Error Instead of Standard Output
Command-line tools often send normal output to standard output (stdout) and errors to standard error (stderr). This makes it easy for users to pipe output to files while still seeing errors in the terminal.
Using eprintln!
The simplest way to write to stderr is eprintln!, which mirrors println!:
fn main() {
eprintln!("error: expected a filename")
}
Writing Directly to stderr
For more control, you can write to std.io.stderr():
import std.io.Error as IoError
import std.io.{ Write }
fn reportError(message: &str): Result<(), IoError> {
var stderr = std.io.stderr()
stderr.writeAll("\(message)\n".asBytes())?
Ok(())
}
This approach is useful when you want to avoid formatting macros or when you need to write binary data.
Why It Matters
Separating stdout and stderr lets users do things like:
cargo run -- file.txt > results.txt
If your program writes errors to stdout, the error messages will end up in the output file. Writing errors to stderr keeps the output clean.