One uses this to send output to stdout:
println!("some output")
I think there is no corresponding macro to do the same for stderr.
One uses this to send output to stdout:
println!("some output")
I think there is no corresponding macro to do the same for stderr.
After Rust 1.19
As of Rust 1.19, you can use the
eprint
andeprintln
macros:This was originally proposed in RFC 1896.
Before Rust 1.19
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:
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:This is a bit much, so let's wrap it back in a macro:
print!
andprintln!
are convenience methods for writing to standard output. There are other macros with the same formatting features available for different tasks:write!
andwriteln!
to write a formatted string to a&mut Writer
format!
to just generate a formattedString
To write to the standard error stream, you can use e.g.
writeln!
like this:It's done so:
You can test it by sending the program output to
/dev/null
to ensure it works (I ignore the warning):Similarly, one can do the following for stdout:
I think this means
println!
is just a convenience: it's shorter and it also allows some formatting. As an example of the latter, the following displays0x400
:While not answering the precise question, maybe it’s of interest that there’s a
log
crate which specifies an interface for leveled logging that other crates (e.g.env_logger
) can fulfill.The output of such logging will be sent to
stderr
, and there are additional benefits for users, such as specifying the log level.This is how using such a logger could look like:
(Example adapted from http://burntsushi.net/rustdoc/env_logger/index.html#example)
Goal
Notes
The other answers generate an unused import warning with the latest nightly, so here's a modern macro that Just Works TM.
Code