首页 > 解决方案 > 重新借用嵌套的可变引用

问题描述

我正在尝试创建对可变引用的可变引用,删除外部引用,然后重用内部引用。但是,我总是遇到某种错误。这是该问题的一个最小化,非常冗长的示例:

#[derive(Clone, Debug)]
struct NoCopy;

fn foo<'a>(vec: &'a mut Vec<NoCopy>) -> &'a mut NoCopy {
    {
        let try_first: Option<&'a mut NoCopy> = vec.first_mut();
        if let Some(first) = try_first {
            return first;
        }
    }

    vec.push(NoCopy);
    vec.first_mut().unwrap()
}

操场

这会产生以下错误:

error[E0499]: cannot borrow `*vec` as mutable more than once at a time
  --> src/lib.rs:12:5
   |
4  | fn foo<'a>(vec: &'a mut Vec<NoCopy>) -> &'a mut NoCopy {
   |        -- lifetime `'a` defined here
5  |     {
6  |         let try_first: Option<&'a mut NoCopy> = vec.first_mut();
   |                        ----------------------   --- first mutable borrow occurs here
   |                        |
   |                        type annotation requires that `*vec` is borrowed for `'a`
...
12 |     vec.push(NoCopy);
   |     ^^^ second mutable borrow occurs here

error[E0499]: cannot borrow `*vec` as mutable more than once at a time
  --> src/lib.rs:13:5
   |
4  | fn foo<'a>(vec: &'a mut Vec<NoCopy>) -> &'a mut NoCopy {
   |        -- lifetime `'a` defined here
5  |     {
6  |         let try_first: Option<&'a mut NoCopy> = vec.first_mut();
   |                        ----------------------   --- first mutable borrow occurs here
   |                        |
   |                        type annotation requires that `*vec` is borrowed for `'a`
...
13 |     vec.first_mut().unwrap()
   |     ^^^ second mutable borrow occurs here

无论我尝试什么,我似乎都无法编译它。我认为这个问题可能与为什么我不能在将 &mut 引用传递给接受泛型类型的函数后重用它?,但我无法弄清楚如何将公认的解决方案应用于此问题。这让我想知道这个错误是否真的是正确的行为(即我的代码是不安全的),但我似乎无法找出代码的任何问题。

我如何让这段代码编译,或者编译器错误是由实际的逻辑问题引起的?

标签: rustborrow-checker

解决方案


推荐阅读