在 Rust 教程代码中获取"error[E0599]: no method named write_fmt found"错误



我正在尝试使用writeln!()而不是println!()宏写入标准输出,这样我就可以优雅地处理I/O错误(例如,当我将长时间运行的输出管道传输到head时(。我在找到了以下片段https://rust-cli.github.io/book/tutorial/output.html#a-关于打印性能的说明,包含在错误处理功能中:

use std::io;
fn main() {
if let Err(error) = run() {
eprintln!("{}", error);
}
}
fn run() -> Result<(), io::Error> {
let stdout = io::stdout(); // get the global stdout entity
let mut handle = io::BufWriter::new(stdout); // wrap that handle in a buffer
writeln!(handle, "foo: {}", 42)?; // add ? if you care about errors here
return Ok(());
}

它在网站";运行此代码";按钮,但当我试图为自己构建它时,我得到了一个编译器错误:

error[E0599]: no method named `write_fmt` found for struct `std::io::BufWriter<std::io::Stdout>` in the current scope
--> src/main.rs:12:5
|
12   |     writeln!(handle, "foo: {}", 42)?; // add ? if you care about errors here
|     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ method not found in `std::io::BufWriter<std::io::Stdout>`
| 
::: /home/hwalters/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/src/libstd/io/mod.rs:1516:8
|
1516 |     fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> Result<()> {
|        --------- the method is available for `std::boxed::Box<std::io::BufWriter<std::io::Stdout>>` here
|
= help: items from traits can only be used if the trait is in scope
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
help: the following trait is implemented but not in scope; perhaps add a `use` for it:
|
1    | use std::io::Write;
|

继续";该方法适用于"提示,我尝试将BufWriter封装在Box中,但这没有任何区别。

我使用的是Rust 2018。我有什么东西不见了吗?

您需要导入std::io::Write特征,如错误所示:

use std::io::Write;

在Rust中,必须导入特性才能使用它们实现的方法。


它在网站上工作"运行此代码";按钮,但当我试图为自己构建它时,我得到了一个编译器错误:

如果您指的是;"关于打印性能的说明";,则它确实包括use std::io::{self, Write};形式的导入。

writeln!宏要求其第一个参数具有write_fmt方法。默认情况下,io::BufWriter<T>不实现此方法,它只为io::BufWriter<T: io::Write>实现,因此要访问该实现,必须将io::Write特性导入到代码中。固定示例:

use std::io;
use std::io::Write; // need to import this trait
fn main() {
if let Err(error) = run() {
eprintln!("{}", error);
}
}
fn run() -> Result<(), io::Error> {
let stdout = io::stdout();
let mut handle = io::BufWriter::new(stdout);
writeln!(handle, "foo: {}", 42)?;
Ok(())
}

操场

相关内容