Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/azure/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Rust 无法编译使用std::io的代码-“std::io”中没有“文件”`_Rust - Fatal编程技术网

Rust 无法编译使用std::io的代码-“std::io”中没有“文件”`

Rust 无法编译使用std::io的代码-“std::io”中没有“文件”`,rust,Rust,我对Rust还很陌生,我只是想通过从文本文件中逐行读取来熟悉io库。我试图编译的示例直接来自网站 使用std::io::BufferedReader; 使用std::io::File; fn main(){ 让path=path::new(“file_test.txt”); 让mut file=BufferedReader::new(file::open(&path)); 对于文件中的行。行(){ 打印!(“{}”,line.unwrap()); } } 当我试图用rustc编译它时,我收到了

我对Rust还很陌生,我只是想通过从文本文件中逐行读取来熟悉io库。我试图编译的示例直接来自网站

使用std::io::BufferedReader;
使用std::io::File;
fn main(){
让path=path::new(“file_test.txt”);
让mut file=BufferedReader::new(file::open(&path));
对于文件中的行。行(){
打印!(“{}”,line.unwrap());
}
}
当我试图用rustc编译它时,我收到了以下错误:

io_test.rs:1:5:1:28错误:未解析的导入`std::io::BufferedReader`。'std::io'中没有'BufferedReader'`
io_测试:1使用std::io::BufferedReader;
^~~~~~~~~~~~~~~~~~~~~~~
io_test.rs:2:5:2:18错误:未解析的导入`std::io::File`。'std::io中没有'File'`
rs:2使用std::io::File;
^~~~~~~~~~~~~
错误:由于之前的两个错误而中止

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

您可能希望导入
std::fs::File
std::io::BufReader
(您还需要在代码中将
BufferedReader
更改为
BufReader

需要注意的一些事项:

  • BufferedReader
    不存在,只有
    BufReader
  • std::io::File
    实际上是
  • 路径
    导入丢失
  • 打开
    文件
    可能会因错误而失败,必须进行处理或展开。在小脚本中,
    unwrap
    可以,但这意味着如果文件丢失,程序将中止
  • 读取行不是一个可变操作,所以编译器会警告您它是不必要的可变操作
  • 要使用
    您需要导入
    使用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());
      }
  }

除了洛吉所说的

  • 使用std::io::BufferedReader
    =>
    使用std::io:{BufReader,BufRead}
  • 使用std::io::File
    =>
    使用std::fs::File
  • 返回一个
    结果
    ,例如,您可能需要
    展开它

。。。它会惊慌失措,因为它在未知文件上展开了一段时间以前的代码<代码>std::io
从那时起就被重写了。哎呀,丹尼尔速度更快,他的答案比我的更详细