为什么重新借用仅适用于取消引用的指针?

Why does re-borrowing only work on de-referenced pointers?

本题及代码改编自。那里的答案解释了重新借用,但没有解释围绕它的约定的原因。

下面对 test 的两次调用似乎是等价的,为什么只有第一个有效?

fn main() {
    let mut string = String::new();
    let ref_string = &mut string;

    // Compiles
    test(&mut *ref_string);

    // Doesn't compile
    test(&mut string);
}

fn test(s: &mut String) {
    s.push('t');
}

您一次只能对一个值有一个可变引用。当您可变地重新借用作为参数时, 微不足道 编译器会发现您不会同时使用 ref_string,因此代码是安全的。

我的印象是可变性有一个 "chain of custody"。 ref_string 是持有者,可以暂时将其交给 &mut *ref_string 创建的临时对象。当超出范围时,可变性将返回给它。就好像代码是:

{
    let x = &mut *ref_string;
    test(x);
}

但是,当您尝试 "go around" 并获取可变引用时,您忽略了监管链。编译器会阻止你,因为它无法平凡地 看出它是安全的。


值得注意的是 non-lexical lifetimes 改善了原来的情况。当启用基于 MIR 的借用检查器时,编译器可以看到 ref_string 在第二次调用 test 时不再被使用,因此将独占访问转移到那里是安全的.