BurntSushi/advent-of-code

writeln!(io::stdout()) vs println

n8henrie opened this issue · 2 comments

As others, I've greatly enjoyed being able to compare your solutions to my own as I (slowly) go through AoC 2018. Thank you!

Is there a reason that you seem to prefer writeln!(io::stdout()) to println!?

Sure. println! panics if it encounters an error, where as
writeln!(io::stdout, "...")? properly propagates the error.

Even programs such as Cargo suffer from this problem. For example:

$ git clone git://github.com/BurntSushi/ripgrep
$ cd ripgrep
$ cargo build

$ cargo run --help | grep
Usage: grep [OPTION]... PATTERNS [FILE]...
Try 'grep --help' for more information.
thread 'main' panicked at 'Error writing Error to stdout: Os { code: 32, kind: BrokenPipe, message: "Broken pipe" }', src/libcore/result.rs:997:5
note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.

$ ./target/debug/rg --help | grep
Usage: grep [OPTION]... PATTERNS [FILE]...
Try 'grep --help' for more information.

ripgrep gets it right, but Cargo doesn't. println! is effectively a footgun in
real command line programs. Cargo is somewhat of an unfair example, since it
isn't often used in pipelines where this matters. But still, there could be
other reasons where writing to stdout fails---and perhaps a panic there is a
good thing. But I don't think panics should be surfaced to end users.

println! is fine in short programs or where this sort of thing doesn't matter,
but I was trying to write idiomatic code, and IMO, idiomatic command line
programs don't panic.