如何避免在不同的比赛武器中两次借用可变的Vec?

时间:2018-12-10 21:21:41

标签: rust

我正在向量中存储一些结构。在一个循环中,我试图处理一些输入,并且在每次迭代中,我都想将一个新项目插入向量中,或者对一个现有元素进行突变(取决于它是否已经在向量中)。

所以我正在尝试做这样的事情。

struct Foo {
    id: char,
    data: i32,
}

fn main() {
    let mut cache: Vec<Foo> = Vec::new();

    for a in vec!['c'] {
        let foo = cache.iter_mut().filter(|s| s.id == a).nth(0);

        match foo {
            Some(f) => {
                f.data = f.data + 1;
            }
            None => {
                cache.push(Foo { id: a, data: 0 });
            }
        }
    }
}

我在None手臂说的错误

error[E0499]: cannot borrow `cache` as mutable more than once at a time
  --> src/main.rs:17:17
   |
10 |         let foo = cache.iter_mut().filter(|s| s.id == a).nth(0);
   |                   ----- first mutable borrow occurs here
...
17 |                 cache.push(Foo { id: a, data: 0 });
   |                 ^^^^^ second mutable borrow occurs here
...
20 |     }
   |     - first borrow ends here

避免此问题的惯用方式是什么?我尝试了以下解决方法,该方法似乎可行,但是感觉很笨拙。

for a in vec!['c'] {
    let mut found = false;

    {
        let step = cache.iter_mut().filter(|s| s.id == a).nth(0);

        match step {
            Some(f) => {
                f.data = f.data + 1;
                found = true;
            }
            None => (),
        }
    }

    if !found {
        cache.push(Foo { id: a, data: 0 });
    }
}

有更简单的解决方案吗?

0 个答案:

没有答案