HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustCritical

How to send output to stderr?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
sendstderrhowoutput

Problem

One uses this to send output to stdout:

println!("some output")


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

Solution

After Rust 1.19

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.

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:

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)
}

Code Snippets

fn main() {
    eprintln!("This is going to standard error!, {}", "awesome");
}
use std::io::Write;

let name = "world";
writeln!(&mut std::io::stderr(), "Hello {}!", name);
use std::io::Write;

let name = "world";
let r = writeln!(&mut std::io::stderr(), "Hello {}!", name);
r.expect("failed printing to stderr");
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)
}

Context

Stack Overflow Q#27588416, score: 118

Revisions (0)

No revisions yet.