使用bufreader.lines()进行for循环后无法使用移动的BufReader

时间:2016-10-08 17:17:43

标签: rust traits

我试图从文件中读取一些行,跳过前几行并打印其余行,但移动后我一直收到有关使用值的错误:

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

fn skip_and_print_file(skip: &usize, path: &Path) {
    let mut skip: usize = *skip;

    if let Ok(file) = File::open(path) {
        let mut buffer = BufReader::new(file);
        for (index, line) in buffer.lines().enumerate() {
            if index >= skip {
                break;
            }
        }
        print_to_stdout(&mut buffer);
    }
}

fn print_to_stdout(mut input: &mut Read) {
    let mut stdout = io::stdout();
    io::copy(&mut input, &mut stdout);
}

fn main() {}

这是我得到的错误:

error[E0382]: use of moved value: `buffer`
  --> src/main.rs:15:30
   |
10 |         for (index, line) in buffer.lines().enumerate() {
   |                              ------ value moved here
...
15 |         print_to_stdout(&mut buffer);
   |                              ^^^^^^ value used here after move
   |
   = note: move occurs because `buffer` has type `std::io::BufReader<std::fs::File>`, which does not implement the `Copy` trait

2 个答案:

答案 0 :(得分:5)

为了避免移动,请使用Read::by_ref() method。这样,您只能借用 BufReader

for (index, line) in buffer.by_ref().lines().enumerate() { ... }
//                         ^^^^^^^^^
// you can still use `buffer` here

答案 1 :(得分:4)

作为Lukas Kalbertodt says,请使用Read::by_ref

这可以防止lines使用BufReader,而不会消耗&mut BufReader。相同的逻辑applies to iterators

您可以只使用Iterator::take,而不是自己实施skip。这必须通过Iterator::count之类的东西来完成:

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

fn skip_and_print_file(skip: usize, path: &Path) {
    if let Ok(file) = File::open(path) {
        let mut buffer = BufReader::new(file);

        for _ in buffer.by_ref().lines().take(skip) {}
        // Or: buffer.by_ref().lines().take(skip).for_each(drop);

        print_to_stdout(&mut buffer);
    }
}

fn print_to_stdout(mut input: &mut Read) {
    let mut stdout = io::stdout();
    io::copy(&mut input, &mut stdout).expect("Unable to copy");
}

fn main() {
    skip_and_print_file(2, Path::new("/etc/hosts"));
}

请注意,没有理由使skip变量可变或甚至传入引用。您也可以接听AsRef<Path>,然后skip_and_print_file的来电者可以直接传入字符串文字。