Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Loops 如何访问BufReader两次?_Loops_Rust_Iterator - Fatal编程技术网

Loops 如何访问BufReader两次?

Loops 如何访问BufReader两次?,loops,rust,iterator,Loops,Rust,Iterator,第二次尝试访问变量语句会导致移动后此处使用的值,我想了解如何存储总计而不会导致此问题 我试图复制迭代器,但我找不到使其工作的方法,也找不到正确的方法 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"); l

第二次尝试访问变量语句会导致移动后此处使用的值
,我想了解如何存储总计而不会导致此问题

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

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);
}

你不能。您需要读取文件两次。首先计算总行数。第二步是处理每条生产线。所以您需要两个
BufReader

extern板条箱正则表达式;
使用std::fs::File;
使用std::io::{BufRead,BufReader};
使用std::path::path;
fn获取文件读取器(路径:&path)->impl BufRead{
BufReader::新建(文件::打开(路径).unwrap())
}
fn main(){
让句子_path=path::new(“csv/test句子.csv”);
让句子=获取文件读取器(&句子路径);
let total=get_file_reader(&statemens_path).lines().count();
用于句子中的(索引,句子)。行()。枚举(){
让线=句子。展开();
println!(“已处理的{},{},索引,总计,行);
}
println!(“总计{}”,总计);
}

如果之前移动了所有权,则无法访问该值。但是,您可以使用检查行,而不更改内行,只更新计数

在通过迭代行找到
计数后,您可以再次迭代它,并根据需要执行逻辑

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

以下是解决方案:

使用std::fs::File;
使用std::io::{BufRead,BufReader,Write};
fn main(){
让path=“lines.txt”;
让mut output=File::create(path).unwrap();
write!(输出,“Rust\n
句子。lines()
是一个迭代器。您可以通过调用
.by_ref()
借用它,而不是使用它:

让mut行=句子。行();
让总数=行。按参考()计数();
用于行中的(索引、句子)。枚举(){
// ...
}

使用此实现,您将整个文件读取到内存中两次,而这不是内存efficient@Websterix内存效率意味着更少的内存使用,此解决方案比将整个文件存储在内存中的解决方案使用更少的内存。这根本不起作用,
by_ref()
不会克隆迭代器,它只会进行变异借用。这个问题的两个答案都是折衷的,你没有很多内存,或者你的文件真的很大,读两遍?或者你的文件大小很小,你有足够的内存,储存整个文件。