rust - 在比赛语句和结果中可变借用

标签 rust borrow-checker

我试图确定容器是否有对象,如果有则返回找到的对象,如果没有则添加它。

我找到了Rust borrow mutable self inside match expression 其中有一个答案表明我正在尝试做的事情不能(不能?)完成。

在我的情况下,我有一些带有 child 向量的对象。我不想暴露对象的内部结构,因为我可能想更改下面的表示。

How can you resolve the need to mutably borrow in different match arms in Rust?似乎表明,如果我的生命周期正确,我也许能够做我想做的事,但我一直无法弄清楚如何做。

以下是我遇到的问题的描述:

fn find_val<'a>(container: &'a mut Vec<i32>, to_find: i32) -> Option<&'a mut i32> {
    for item in container.iter_mut() {
        if *item == to_find {
            return Some(item);
        }
    }

    None
}

fn main() {
    let mut container = Vec::<i32>::new();
    container.push(1);
    container.push(2);
    container.push(3);

    let to_find = 4;

    match find_val(&mut container, to_find) {
        Some(x) => {
            println!("Found {}", x);
        }
        _ => {
            container.push(to_find);
            println!("Added {}", to_find);
        }
    }
}

playground

我得到的错误是:

error[E0499]: cannot borrow `container` as mutable more than once at a time
  --> src/main.rs:24:13
   |
19 |     match find_val(&mut container, to_find) {
   |                         --------- first mutable borrow occurs here
...
24 |             container.push(to_find);
   |             ^^^^^^^^^ second mutable borrow occurs here
...
27 |     }
   |     - first borrow ends here

最佳答案

将更改放入函数中,并使用提前返回而不是 else 分支:

fn find_val_or_insert(container: &mut Vec<i32>, to_find: i32) {
    if let Some(x) = find_val(&container, to_find) {
        println!("Found {}", x);
        return; // <- return here instead of an else branch
    }
    container.push(to_find);
    println!("Added {}", to_find);
}

另请参阅Mutable borrow more than onceHow to update-or-insert on a Vec?

关于rust - 在比赛语句和结果中可变借用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49247879/

相关文章:

generics - 如何告诉编译器内部字段实现了特征或通用特征只有 2 个变体?

rust - 如何在Rust中使用Tera创建数组?

rust - cargo 未能为rustc_version选择版本

rust - 我们什么时候应该在 Rust 中使用 unwrap 和 expect

rust - `dyn` 与绝对路径一起使用时出现错误 [E0433]

rust - 为什么代码编译需要这些确切的生命周期?

rust - 为什么通过提取方法进行重构会触发借用检查器错误?

rust - 如何使用滑动窗口对生成迭代器?

rust - 如何解决 RefCell 问题?

loops - E0597试图在向量上循环