简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM