如何将输出发送到标准错误? [英] How to send output to stderr?

查看:59
本文介绍了如何将输出发送到标准错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用它来将输出发送到标准输出:

One uses this to send output to stdout:

println!("some output")

我认为没有相应的宏可以为 stderr 做同样的事情.

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

推荐答案

Rust 1.19 之后

从 Rust 1.19 开始,您可以使用 eprinteprintln 宏:

fn main() {
    eprintln!("This is going to standard error!, {}", "awesome");
}

这最初是在 RFC 1896.

你可以看到println! 的实现来深入了解它是如何工作的,但是当我第一次阅读它时有点不知所措.

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.

您可以使用类似的宏将内容格式化为 stderr:

You can format stuff to stderr using similar macros though:

use std::io::Write;

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

这会给你一个必须使用的未使用结果警告,因为打印到 IO 可能会失败(这不是我们通常在打印时考虑的事情!).我们可以看到现有的方法 只是恐慌,所以我们可以更新我们的代码来做同样的事情:

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

这篇关于如何将输出发送到标准错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆