循环中的可变借用是不允许的 iff 包装器类型 impls Drop

问题描述 投票:0回答:0

考虑以下最小示例:

struct Wrapper<'a>(&'a mut i32);
impl<'a> Drop for Wrapper<'a> {
    fn drop(&mut self) {}
}
fn main() {
    let mut a = 0;
    let mut f = None;
    for _ in 0..100 {
        f = match f {
            None => Some(Wrapper(&mut a)),
            Some(a) => Some(a),
        };
    }
}

这会产生以下编译器错误:

error[E0499]: cannot borrow `a` as mutable more than once at a time
  --> src/main.rs:10:34
   |
9  |         f = match f {
   |                   - first borrow used here, in later iteration of loop
10 |             None => Some(Wrapper(&mut a)),
   |                                  ^^^^^^ `a` was mutably borrowed here in the previous iteration of the loop

但是,当删除

Drop
Wrapper
实现时,代码片段编译得很好。

这是编译器中的错误吗?如果不是,这似乎是一个主要的 semver-hazard,其中为一个类型实现 Drop 可能会破坏下游用户的代码。

rust borrow-checker
© www.soinside.com 2019 - 2024. All rights reserved.