在嵌套循环中从 BufReader 读取错误

Error reading from BufReader in nested loops

我一直在用 Rust 开发一个程序,从本地文本文件中读取单独的行,将行划分为字符向量并执行一些其他操作。这是我的代码片段:

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

fn main() {
 
   // ----<code snippet>-----  

    let input_file = File::open("--<text file location>--").unwrap();
    let input_file = BufReader::new(input_file);
    let mut temp2 = String::new();
    let mut counter = 0;

    while counter < 12 {
        for line in input_file.lines() {
            let input_line = line.expect("Failed to read line");
            let temp: Vec<char> = input_line.chars().collect::<Vec<_>>();
            temp2.push(temp[counter]);
        }

      //-----<program continues without any issues>-------

这是 Cargo 中显示的错误消息:

error[E0382]: use of moved value: `input_file`
    --> src\main.rs:48:21
     |
42   |     let input_file = BufReader::new(input_file);
     |         ---------- move occurs because `input_file` has type `BufReader<File>`, which does not implement the `Copy` trait
...
48   |         for line in input_file.lines() {
     |                     ^^^^^^^^^^ ------- `input_file` moved due to this method call, in previous iteration of loop        
     |
note: this function takes ownership of the receiver `self`, which moves `input_file`
    --> C:\Users\Gumbi\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib/rustlib/src/rust\library\std\src\io\mod.rs:2258:14 
     |
2258 |     fn lines(self) -> Lines<Self>
     |              ^^^^

error[E0382]: borrow of moved value: `temp2`
  --> src\main.rs:51:13
   |
44 |     let mut temp2 = String::new();
   |         --------- move occurs because `temp2` has type `String`, which does not implement the `Copy` trait
...
51 |             temp2.push(temp[counter]);
   |             ^^^^^ value borrowed here after move
...
54 |         let temp3 = most_common_digit(temp2);
   |                                       ----- value moved here, in previous iteration of loop

我知道所有权和借用的基础知识,但我无法理解这段代码中的问题所在。谁能帮我知道我哪里出错了?

问题是 input_file 被移动到 while 循环范围内。而是使用可以在每次迭代中删除的中介 &mut

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

fn main() {
    // ----<code snippet>-----

    let input_file = File::open("--<text file location>--").unwrap();
    let mut input_file = BufReader::new(input_file);
    let mut temp2 = String::new();
    let mut counter = 0;

    while counter < 12 {
        let mut input_file_ref = &mut input_file;

        for line in input_file_ref.lines() {
            let input_line = line.expect("Failed to read line");
            let temp: Vec<char> = input_line.chars().collect::<Vec<_>>();
            temp2.push(temp[counter]);
        }
    }
}

Playground