struct container<'x> {
value: &'x i32,
}
impl<'x> container<'x> {
fn f(&'x mut self) {}
}
fn main() {
let v = 1;
let mut a = container{value: &v}; // 'a----------+
{ // |
let a1 = & mut a; //'b---------------------+ |
a1.f(); // | |
//end--------------------------------------+ |
} // |
//end--------------------------------------------+
let p = & mut a; // suppose to be 'c but 'b break out from block?
}
编译时不会出现错误:
cannot borrow 'a' as mutable more than once at a time
。
首先在这里借用:
let a1 = & mut a;
,它位于区块中。生命应该已经结束了,但它却在某个地方爆发了?
让我们逐个查看您的代码。 第一个:
struct container<'x> {
value: &'x i32,
}
上面的代码意味着
&i32
必须至少与container
一样长。
impl<'x> container<'x> {
fn f(&'x mut self) {}
}
此处,您为
'x
生命周期和 command
方法参数生命周期指定了相同的生命周期参数 f
。基本上,您说对 self
的可变引用必须至少与内部 &i32
存在一样长(或者换句话说,只要 container
存在)。
这就是为什么即使在区块结束后它仍然可以被借用。
当你写这样的代码时:
impl<'x> container<'x> {
fn f(&mut self) {}
}
然后新的生命周期将被分配给
&mut self
并且代码将编译。对于编译器来说,上面的代码看起来像这样:
impl<'x> container<'x> {
fn f<'b>(&'b mut self) {}
}