Skip to content

Instantly share code, notes, and snippets.

@jwilm
Last active June 29, 2016 20:05
Show Gist options
  • Save jwilm/16ce667076b854fbae55568f340c6a84 to your computer and use it in GitHub Desktop.
Save jwilm/16ce667076b854fbae55568f340c6a84 to your computer and use it in GitHub Desktop.
Improved println!
/// Improved println! macro that allows specifying stdout or stderr
///
/// # Examples
///
/// Printing to stdout works like normal
/// ```rust
/// zprintln!("Hello, zprintln!");
/// ```
///
/// Printing to stderr works by passing a special argument
/// ```rust
/// zprintln!(stderr, "Hello, stderr!");
/// ```
macro_rules! zprintln {
(stdout, $($arg:tt)*) => {
println!($($arg)*);
};
(stderr, $($arg:tt)*) => {{
use std::io::Write;
writeln!(::std::io::stderr(), $($arg)*).unwrap();
}};
($($arg:tt)*) => {
println!($($arg)*);
};
}
fn main() {
zprintln!("normal shows up on stdout");
zprintln!("normal shows up on stdout with arg: {}", 1);
zprintln!(stdout, "with stdout goes to stdout: {}", 1);
zprintln!(stderr, "with stderr goes to stderr: {}", 2);
}
@jwilm
Copy link
Author

jwilm commented Jun 29, 2016

Output:

jwilm@Joes-MBP ➜  ~/sandbox/zprintln/target/debug  ./zprintln > /dev/null
with stderr goes to stderr: 2
jwilm@Joes-MBP ➜  ~/sandbox/zprintln/target/debug  ./zprintln 2> /dev/null
normal shows up on stdout
normal shows up on stdout with arg: 1
with stdout goes to stdout: 1
jwilm@Joes-MBP ➜  ~/sandbox/zprintln/target/debug

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment