gpt4 book ai didi

loops - 如何访问 BufReader 两次?

转载 作者:行者123 更新时间:2023-11-29 08:04:42 25 4
gpt4 key购买 nike

第二次尝试访问变量sentences 导致value used here after move ,我想了解如何在不引起此问题的情况下存储总数。

我试图复制迭代器,但找不到使其工作的方法或正确的方法。

extern crate regex;

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

fn main() {
let sentences_path = Path::new("csv/testSentences.csv");
let sentences = BufReader::new(File::open(&sentences_path).unwrap());

let total = sentences.lines().count();

for (index, sentence) in sentences.lines().enumerate() {
let line = sentence.unwrap();
println!("Processed {} of {}, {}", index, total, line);
}

println!("Total {}", total);
}

最佳答案

如果之前移动了所有权,您将无法访问该值。但是,您可以使用 inspect 检查您的线路不改变内线,只更新计数。

通过迭代 Lines 找到 count 后,您可以再次迭代它并按照您的意愿执行逻辑。

出现此编译器错误的主要原因是:count函数会消耗您使用的行,并且您无法再次访问您的变量,因为它已被消耗。

解决方法如下:

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

fn main() {
let path = "lines.txt";

let mut output = File::create(path).unwrap();
write!(output, "Rust\n💖\nFun").unwrap();

let input = File::open(path).unwrap();
let buffered = BufReader::new(input);

let lines: Vec<_> = buffered.lines().collect();
let total = lines.len();

for (index, sentence) in lines.into_iter().enumerate() {
let line = sentence.unwrap();
println!("Processed {} of {}, {}", index, total, line);
}

println!("Total {}", total);
}

Playground

通过这种方式,您不需要读取文件两次。您读取文件,将其放入内存,然后只迭代两次。

关于loops - 如何访问 BufReader 两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56620265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com