gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:33:43 25 4
gpt4 key购买 nike

我正在尝试使用writeln!()而不是println!()宏写入标准输出,因此我可以优雅地处理I/O错误(例如,将长期运行的输出通过管道传输到head)。我在https://rust-cli.github.io/book/tutorial/output.html#a-note-on-printing-performance处找到了以下代码段,并将其包装在一个错误处理函数中:

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中,必须导入特征才能使用它们实现的方法。

It works on the website "run this code" button, but when I try to build it for myself, I get a compiler error:


如果您要引用链接到的“ A note on printing performance”,那么它确实包括 use std::io::{self, Write};形式的导入。

关于rust - 在Rust教程代码中获取 “error[E0599]: no method named write_fmt found”错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65256507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com