Unable to compile code that uses std :: io. In `std :: io` there is no` File`

I am new to Rust and I was just trying to get to know the io library by doing a basic phased reading from a text file. The example that I tried to compile was directly from the site.

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 were 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 this part of the problem is. I really appreciate any help. Perhaps this is just some simple mistake or mistake on my part.

+2
source share
3 answers

Some notes:

  • BufferedReader does not exist, only BufReader .
  • std::io::File is actually std::fs::File .
  • Path missing import.
  • Opening File may fail and must be processed or expanded. In a small script, unwrap fine, but that means the file is missing, your program is interrupted.
  • Reading lines is not a mutable operation, so the compiler will warn you that it is uselessly changed.
  • To use lines , you need to import use std::io::File .

Ready 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()); } } 
+9
source

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 unwrap it

playpen link ... which panics because it is unwrap on an unknown file

+3
source

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

+1
source

Source: https://habr.com/ru/post/973692/


All Articles