简体   繁体   English

Rust - 从方法中获取值而不借用(计算文件的行数)

[英]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.我是 rust 的新手,我不知道如何解决。 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);调用BufReader::new(file_handle); consumes the file_handle and calling buffered.lines() consumes buffered .消耗file_handle并调用buffered.lines()消耗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(())
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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