
#[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 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 ) |