How to send output to stderr?

后端 未结 5 1933
感动是毒
感动是毒 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条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-15 03:59

    Goal

    stderr!("Code {}: Danger, Will Robinson!  Danger!", 42);
    

    Notes

    The other answers generate an unused import warning with the latest nightly, so here's a modern macro that Just Works TM.

    Code

    macro_rules! stderr {
        ($($arg:tt)*) => (
            use std::io::Write;
            match writeln!(&mut ::std::io::stderr(), $($arg)* ) {
                Ok(_) => {},
                Err(x) => panic!("Unable to write to stderr (file handle closed?): {}", x),
            }
        )
    }
    

提交回复
热议问题