gpt4 book ai didi

rust - 无法编译使用 std::io 的代码 - `File` 中没有 `std::io`

转载 作者:行者123 更新时间:2023-11-29 08:01:35 24 4
gpt4 key购买 nike

我是 Rust 的新手,我只是想通过从文本文件执行基本的逐行读取来熟悉 io 库。我试图编译的示例直接来自网站。

use std::io::BufferedReader;
use std::io::File;

fn main() {
let path = Path::new("file_test.txt");
let mut file = BufferedReader::new(File::open(&path));
for line in file.lines() {
print!("{}", line.unwrap());
}
}

当我尝试用 rustc 编译它时,这些是我收到的错误:

io_test.rs:1:5: 1:28 error: unresolved import `std::io::BufferedReader`. There is no `BufferedReader` in `std::io`
io_test.rs:1 use std::io::BufferedReader;
^~~~~~~~~~~~~~~~~~~~~~~
io_test.rs:2:5: 2:18 error: unresolved import `std::io::File`. There is no `File` in `std::io`
io_test.rs:2 use std::io::File;
^~~~~~~~~~~~~
error: aborting due to 2 previous errors

我使用的是 Ubuntu 14.04,我不知道这是否是问题的一部分。我真的很感激任何帮助。也许这只是我的一些简单错误或错误。

最佳答案

一些注意事项:

  • BufferedReader 不存在,只有 BufReader
  • std::io::File 实际上是 std::fs::File .
  • 路径 导入丢失。
  • 打开 File 可能因错误而失败,必须进行处理或解包。在一个小脚本中 unwrap 很好,但这意味着如果文件丢失你的程序就会中止。
  • 读取行不是可变操作,因此编译器会警告您它是不必要的可变操作。
  • 要使用lines,您需要导入use std::io::File

完成代码:

  use std::io::{BufReader,BufRead};
use std::fs::File;
use std::path::Path;

fn main() {
let path = Path::new("file_test.txt");
let file = BufReader::new(File::open(&path).unwrap());
for line in file.lines() {
print!("{}", line.unwrap());
}
}

关于rust - 无法编译使用 std::io 的代码 - `File` 中没有 `std::io`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29888088/

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