One uses this to send output to stdout:
println!("some output")
I think there is no corresponding macro to do the same for stderr.
The regular output is sent to Standard Out (STDOUT) and the error messages are sent to Standard Error (STDERR). When you redirect console output using the > symbol, you are only redirecting STDOUT. In order to redirect STDERR, you have to specify 2> for the redirection symbol.
Redirecting stdout and stderr to a file: The I/O streams can be redirected by putting the n> operator in use, where n is the file descriptor number. For redirecting stdout, we use “1>” and for stderr, “2>” is added as an operator. We have created a file named “sample.
As of Rust 1.19, you can use the eprint
and eprintln
macros:
fn main() { eprintln!("This is going to standard error!, {}", "awesome"); }
This was originally proposed in RFC 1896.
You can see the implementation of println!
to dive into exactly how it works, but it was a bit overwhelming when I first read it.
You can format stuff to stderr using similar macros though:
use std::io::Write; let name = "world"; writeln!(&mut std::io::stderr(), "Hello {}!", name);
This will give you a unused result which must be used
warning though, as printing to IO can fail (this is not something we usually think about when printing!). We can see that the existing methods simply panic in this case, so we can update our code to do the same:
use std::io::Write; let name = "world"; let r = writeln!(&mut std::io::stderr(), "Hello {}!", name); r.expect("failed printing to stderr");
This is a bit much, so let's wrap it back in a macro:
use std::io::Write; macro_rules! println_stderr( ($($arg:tt)*) => { { let r = writeln!(&mut ::std::io::stderr(), $($arg)*); r.expect("failed printing to stderr"); } } ); fn main() { let name = "world"; println_stderr!("Hello {}!", name) }
print!
and println!
are convenience methods for writing to standard output. There are other macros with the same formatting features available for different tasks:
write!
and writeln!
to write a formatted string to a &mut Writer
format!
to just generate a formatted String
To write to the standard error stream, you can use e.g. writeln!
like this:
use std::io::Write; fn main() { let mut stderr = std::io::stderr(); writeln!(&mut stderr, "Error!").unwrap(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With