mapet
mapet

Reputation: 31

Rust - Get value from method without borrowing (count the lines of file)

I'm quite new in rust and I have no idea how to workaround. The code is:

let input = File::open(file_path)?;
let buffered = BufReader::new(input);

let line_count = buffered.lines().count();

 for (nr, line) in buffered.lines().enumerate() {
    print!("\rLOADED: [{}/{}]", nr, line_count);
    // do something...
}

The error I've got:

let buffered = BufReader::new(input);
    -------- move occurs because `buffered` has type `std::io::BufReader<std::fs::File>`, which does not implement the `Copy` trait

let line_count = buffered.lines().count();
                 -------- value moved here
  
for (nr, line) in buffered.lines().enumerate() {
                  ^^^^^^^^ value used here after move

Please help, I'm stuck on this.

Upvotes: 3

Views: 2397

Answers (1)

pretzelhammer
pretzelhammer

Reputation: 15115

Calling BufReader::new(file_handle); consumes the file_handle and calling buffered.lines() consumes buffered. There might be a more efficient, clever, or elegant way to do this but you can open and iterate over the file twice if you want to first get the full line count:

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

fn main() -> io::Result<()> {
    let file_path = "input.txt";
    let input = File::open(file_path)?;
    let buffered = BufReader::new(input);
    let line_count = buffered.lines().count();

    let input = File::open(file_path)?;
    let buffered = BufReader::new(input);
    for (nr, line) in buffered.lines().enumerate() {
        println!("LOADED: [{}/{}]", nr, line_count);
    }

    Ok(())
}

Upvotes: 2

Related Questions