Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

rust - Cannot use moved BufReader after for loop with bufreader.lines()

I'm trying to read some lines from a file, skipping the first few and printing the rest, but I keep getting errors about used value after move:

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

This is the error I'm getting:

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In order to avoid the move, use the Read::by_ref() method. That way, you only borrow the BufReader:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...