我正在尝试从文件中读取一些行,跳过前几行并打印其余行,但移动后我不断收到有关使用值的错误:
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() {}
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误:
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
Run Code Online (Sandbox Code Playgroud)
She*_*ter 11
正如Lukas Kalbertodt 所说,使用Read::by_ref.
这可以防止lines消耗BufReader,而是消耗&mut BufReader。同样的逻辑适用于迭代器。
相反,实施的skip自己,你可以使用Iterator::take。这必须通过 for 循环来完成:
use std::{
fs::File,
io::{self, BufRead, BufReader, Read},
path::Path,
};
fn skip_and_print_file(skip: usize, path: impl AsRef<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(buffer);
}
}
fn print_to_stdout(mut input: impl Read) {
let mut stdout = io::stdout();
io::copy(&mut input, &mut stdout).expect("Unable to copy");
}
fn main() {
skip_and_print_file(2, "/etc/hosts");
}
Run Code Online (Sandbox Code Playgroud)
请注意,没有理由使skip变量可变甚至传入引用。你也可以接受,AsRef<Path>然后调用者skip_and_print_file可以只传入一个字符串文字。
为了避免移动,请使用该Read::by_ref()方法.这样一来,你只借了BufReader:
for (index, line) in buffer.by_ref().lines().enumerate() { ... }
// ^^^^^^^^^
// you can still use `buffer` here
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1507 次 |
| 最近记录: |