问下各位大佬,关于 Rust 生命周期的一个疑惑

2019-01-26 17:12:02 +08:00
 VDimos
#[derive(Debug)]
struct Foo;

impl Foo {
    fn borrow(&mut self) -> &Self {
        &*self
    }
}

fn main() {
    let mut foo = Foo;
    let a = foo.borrow();
}

按照官方的文档,生命周期应该会被展开成以下的伪代码

#[derive(Debug)]
struct Foo;

impl Foo {
    fn borrow<'a>(&'a mut self) -> &'a Self {
        &'a *self
    }
}

fn main() {
    'b: {
        let mut foo = Foo;
        'c: {
            let a = Foo::borrow::<'c>(&'c mut foo);
        }
    }
}

按照官方的说明,同一 Context 里面,不允许同事存在一个可变和不可变应用。在这个例子里面,&mut self 和&Self 都存在于同一个‘ c 生命周期作用的 Context 里面,这样不是违反了这个规则吗?但是事实是可以运行。 难道是因为 Self 和 self 不能表示为同一个变量吗?

4015 次点击
所在节点    Rust
1 条回复
quinoa42
2019-01-26 18:11:25 +08:00
foo 是 mut own 了 Foo,而不是 mut reference
一个简单的例子:
```rust
pub fn main() {
let mut x = 4;
let y : &mut u32 = &mut x;
}
```

Borrowing rule 说的是:

> At any given time, you can have either one mutable reference or any number of immutable references.
> References must always be valid.

这里两条都满足了,但是如果在定义了 mutable reference 之后通过原来的 mutable owned variable 来修改值会报错:

```rust
pub fn main() {
let mut x = 4;
let y : &mut u32 = &mut x;
x = 5;
}
```

因为这破坏了第二条原则(详见 E0506 )

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/530861

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX