一生摆脱封锁? [重复]

问题描述 投票:0回答:1
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;
,它位于区块中。生命应该已经结束了,但它却在某个地方爆发了?

作为 Pavlo Myroniuk 答案的后续,请考虑:

fn i32_f<'a>(k: &'a mut i32) {}

fn main() {
    let mut v:i32 = 1;
    let mut i32_a = &mut v;
    { //                                             |
        let i32_a1 = & mut i32_a; //'b-------------+ |
        i32_f(i32_a1);  //                         | |
        //end--------------------------------------+ |
    } //                                             |
    //end--------------------------------------------+
    let i32_p = & mut i32_a; // works
}

如果

container
的引用可以在块之后存在,为什么
i32
的引用不能这样做?这似乎打破了生命周期的一致性。

rust block lifetime
1个回答
3
投票

让我们逐个查看您的代码。 第一个:

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) {}
}
© www.soinside.com 2019 - 2024. All rights reserved.