为什么我不能从枚举中可变地借用一个原语?

Why can't I mutably borrow a primitive from an enum?

我希望能够在 Foo 枚举中获得对 Bar 中包装的 usize 的引用(不可变和可变):

use Foo::*;

#[derive(Debug, PartialEq, Clone)]
pub enum Foo {
    Bar(usize)
}

impl Foo {
    /* this works */
    fn get_bar_ref(&self) -> &usize {
        match *self {
            Bar(ref n) => &n
        }
    }

    /* this doesn't */
    fn get_bar_ref_mut(&mut self) -> &mut usize {
        match *self {
            Bar(ref mut n) => &mut n
        }
    }
}

但是我无法获取可变引用,因为:

n does not live long enough

我能够提供类似函数的两种变体来访问 Foo 的其他内容,这些内容是 Boxed - 为什么可变借用(以及为什么只有它)会因未装箱的原语而失败?

您需要将 Bar(ref mut n) => &mut n 替换为 Bar(ref mut n) => n

当您在 Bar(ref mut n) 中使用 ref mut n 时,它会创建一个可变的 引用 Bar 中的数据,所以 n 的类型是 &mut usize。 然后你尝试return&mut n&mut &mut u32类型。

This part is most likely incorrect.

Now deref coercion kicks in and converts &mut n into &mut *n, creating a temporary value *n of type usize, which doesn't live long enough.

这些示例显示了示例问题:

fn implicit_reborrow<T>(x: &mut T) -> &mut T {
    x
}

fn explicit_reborrow<T>(x: &mut T) -> &mut T {
    &mut *x
}

fn implicit_reborrow_bad<T>(x: &mut T) -> &mut T {
    &mut x
}

fn explicit_reborrow_bad<T>(x: &mut T) -> &mut T {
    &mut **&mut x
}

explicit_ 版本显示了编译器通过 deref coercions 推导出的内容。
_bad 版本都以完全相同的方式出错,而其他两个版本编译。

这要么是错误,要么是当前在编译器中实现生命周期的方式的限制。 &mut TT 上的不变性可能 与它有关,因为它导致 &mut &'a mut T'a 上不变并且因此 在推理过程中比共享引用 (&&'a T) 情况下更具限制性,即使 在这种情况下 严格是不必要的。