重新借用嵌套的可变引用

时间:2020-03-04 18:11:53

标签: rust borrow-checker

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

#[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()
}

Playground

这会产生以下错误:

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

无论我尝试什么,我似乎都无法编译它。我以为这个问题可能与Why can't I reuse a &mut reference after passing it to a function that accepts a generic type?有关,但是我无法弄清楚如何对该问题应用公认的解决方案。这使我想知道错误是否实际上是正确的行为(即我的代码是不安全的),但是我似乎无法找出代码的任何问题。

如何获取此代码进行编译,或者编译器错误是由实际的逻辑问题引起的?

0 个答案:

没有答案