A lot of command-line tools let you use -
for standard input or standard output. Is there an idiomatic way to support that in Rust?
It looks like the most common way to handle command-line arguments is clap
. If I just want to handle paths and donʼt want to special-case -
, I can use
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use clap::Parser;
#[derive(clap::Parser, Debug)]
struct Args {
#[clap(parse(from_os_str))]
output: PathBuf,
}
fn main() -> std::io::Result<()> {
let args = Args::parse();
let mut file = File::create(args.output)?;
file.write_all(b"Hello, world!")?;
Ok(())
}
However, to handle the case of -
being stdout, itʼs more complicated. The type of file
now needs to be Box<dyn Write>
since stdout()
is not a File
, and itʼs somewhat complicated to set it correctly. Not difficult, but the sort of boilerplate that needs to be copied several times and is easy to mess up.
Is there an idiomatic way to handle this?