如何告诉借用检查器已清除的 Vec 不包含借用? [英] How to tell the borrow checker that a cleared Vec contains no borrows?

查看:30
本文介绍了如何告诉借用检查器已清除的 Vec 不包含借用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个巨大的 TSV(制表符分隔值)文件,并希望尽可能高效地执行此操作.为此,我想通过在循环之前预先分配它来防止为每一行分配一个新的 Vec :

I'm processing a massive TSV (tab separated values) file and want to do this as efficiently as possible. To that end, I thought I'd prevent allocation of a new Vec for every line by pre-allocating it before the loop:

let mut line = String::new();
let mut fields = Vec::with_capacity(headers.len());
while reader.read_line(&mut line)? > 0 {
    fields.extend(line.split('\t'));
    // do something with fields
    fields.clear();
}

自然地,借用检查器不会被逗乐,因为我们正在覆盖 linefields 可能仍然有引用:

Naturally, the borrow checker isn't amused, because we're overwriting line while fields may still have references into it:

error[E0502]: cannot borrow `line` as mutable because it is also borrowed as immutable
  --> src/main.rs:66:28
   |
66 |     while reader.read_line(&mut line)? > 0 {
   |                            ^^^^^^^^^ mutable borrow occurs here
67 |         fields.extend(line.split('\t'));
   |         ------        ---- immutable borrow occurs here
   |         |
   |         immutable borrow later used here

(游乐场)

这实际上不是问题,因为 fields.clear(); 删除了所有引用,因此在循环开始时 read_line(&mut line)被调用,fields 实际上并没有从 line 借用任何东西.

This isn't actually a problem because fields.clear(); removes all references, so at the start of the loop when read_line(&mut line) is called, fields does not actually borrow anything from line.

但是我如何通知借阅检查员这一点?

But how do I inform the borrow checker of this?

推荐答案

您的问题看起来与 这篇文章.

除了那里的答案(生命周期变换、引用单元格)之外,根据您注释掉的复杂操作,您可能根本不需要存储对 line 的引用.例如,考虑对您的 Playground 代码进行以下修改:

In addition to the answers there (lifetime transmutations, refcells), depending on the Complex Operation you commented out, you might not need to store references to line at all. Consider, for example, the following modification of your playground code:

use std::io::BufRead;

fn main() -> Result<(), std::io::Error> {
    let headers = vec![1,2,3,4];
    let mut reader = std::io::BufReader::new(std::fs::File::open("foo.txt")?);
    let mut fields = Vec::with_capacity(headers.len());
    loop {
        let mut line = String::new();
        if reader.read_line(&mut line)? == 0 {
            break;
        }
        fields.push(0);
        fields.extend(line.match_indices('\t').map(|x| x.0 + 1));
        // do something with fields
        // each element of fields starts a field; you can use the next
        // element of fields to find the end of the field.
        // (make sure to account for the \t, and the last field having no
        // 'next' element in fields.
        fields.clear();
    }
    Ok(())
}

这篇关于如何告诉借用检查器已清除的 Vec 不包含借用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆