V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
VDimos
V2EX  ›  Rust

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

  •  
  •   VDimos · 2019-01-26 17:12:02 +08:00 · 3984 次点击
    这是一个创建于 1888 天前的主题,其中的信息可能已经有所发展或是发生改变。
    #[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 不能表示为同一个变量吗?

    1 条回复    2019-01-26 18:11:25 +08:00
    quinoa42
        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 )
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2049 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 16:15 · PVG 00:15 · LAX 09:15 · JFK 12:15
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.