Cannot compile code that uses std::io - There is n

2019-04-13 05:00发布

问题:

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());
    }
}

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

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.

回答1:

Some things to note:

  • 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.

Finished code:

  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());
      }
  }


回答2:

In addition to what llogiq said

  • use std::io::BufferedReader => use std::io::{BufReader, BufRead}
  • use std::io::File => use std::fs::File
  • File::open returns a Result so you probably need to unwrap it for instance

playpen link ... which panics because it unwraps on unknown file



回答3:

You probably want to import std::fs::File and std::io::BufReader (You'll also need to change BufferedReader to BufReader in your code).



标签: rust