无法编译使用 std::io 的代码 - `std::io` 中没有 `File` [英] Cannot compile code that uses std::io - There is no `File` in `std::io`

查看:41
本文介绍了无法编译使用 std::io 的代码 - `std::io` 中没有 `File`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am pretty new to Rust, and I was just trying to get familiar with the io library by performing a basic line-by-line read from a text file. The example I was trying to compile was straight from the website.

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 编译它时,我收到了以下错误:

When I tried to compile it with rustc, these are the errors I received:

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,我不知道这是否是问题的一部分.我真的很感激任何帮助.也许这只是我的一些简单错误或错误.

I am using Ubuntu 14.04, and I have no idea if that's part of the problem. I really appreciate any help. Perhaps its just some simple error or mistake on my part.

推荐答案

注意事项:

  • BufferedReader 不存在,只有 BufReader.
  • std::io::File 实际上是 std::fs::File.
  • Path 导入丢失.
  • 打开File 可能会因错误而失败,必须进行处理或解包.在一个小脚本中 unwrap 很好,但这意味着如果文件丢失,你的程序就会中止.
  • 读取行不是可变操作,因此编译器会警告您它是不必要的可变操作.
  • 要使用lines,您需要导入use std::io::File.
  • BufferedReader doesn't exist, there is only BufReader.
  • std::io::File is actually std::fs::File.
  • Path import is missing.
  • Opening File can fail with error and has to be handled or unwrapped. In a small script unwrap is fine, but it means if the file is missing your program aborts.
  • Reading lines, isn't a mutable operation, so compiler will warn you of it being needlessly mutable.
  • To use lines you need to import 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());
      }
  }

这篇关于无法编译使用 std::io 的代码 - `std::io` 中没有 `File`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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