How to send output to stderr?

后端 未结 5 1934
感动是毒
感动是毒 2020-12-15 02:55

One uses this to send output to stdout:

println!(\"some output\")

I think there is no corresponding macro to do the same for stderr.

5条回答
  •  旧时难觅i
    2020-12-15 03:55

    It's done so:

    use std::io::Write;
    
    fn main() {
        std::io::stderr().write(b"some output\n");
    }
    

    You can test it by sending the program output to /dev/null to ensure it works (I ignore the warning):

    $ rustc foo.rs && ./foo > /dev/null
    foo.rs:4:5: 4:42 warning: unused result which must be used, #[warn(unused_must_use)] on by default
    foo.rs:4     io::stderr().write(b"some output\n");
                 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    some output
    

    Similarly, one can do the following for stdout:

    use std::io::Write;
    
    fn main() {
        std::io::stdout().write(b"some output\n");
    }
    

    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 displays 0x400:

    println!("0x{:x}", 1024u)
    

提交回复
热议问题