且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么可变参考没有移到这里?

更新时间:2021-09-09 21:35:21

实际上可能有充分的理由.

There might actually be a good reason for this.

&mut T实际上不是 一种类型:所有借用都经过某些(可能无法表达)生命周期的参数化.

&mut T isn't actually a type: all borrows are parametrized by some (potentially inexpressible) lifetime.

当一个人写

fn move_try(val: &mut ()) {
    { let new = val; }
    *val
}

fn main() {
    move_try(&mut ());
}

类型推断引擎推断typeof new == typeof val,因此它们共享原始生存期.这意味着从new借用直到val借用才结束.

the type inference engine infers typeof new == typeof val, so they share the original lifetime. This means the borrow from new does not end until the borrow from val does.

这意味着它等同于

fn move_try<'a>(val: &'a mut ()) {
    { let new: &'a mut _ = val; }
    *val
}

fn main() {
    move_try(&mut ());
}

但是,当你写

fn move_try(val: &mut ()) {
    { let new: &mut _ = val; }
    *val
}

fn main() {
    move_try(&mut ());
}

发生强制转换-与使指针强制可变性消失的方法相同.这意味着寿命是某些(看似无法指定)'b < 'a.这涉及强制转换,因此涉及重新借入,因此重新借入能够超出范围.

a cast happens - the same kind of thing that lets you cast away pointer mutability. This means that the lifetime is some (seemingly unspecifiable) 'b < 'a. This involves a cast, and thus a reborrow, and so the reborrow is able to fall out of scope.

总是重借的规则可能会更好,但是显式声明并不太成问题.

An always-reborrow rule would probably be nicer, but explicit declaration isn't too problematic.