lnc*_*ncr 4 struct lifetime rust
我最近遇到了一个错误,只需通过更改即可解决
impl<'a> Foo<'a> {
fn foo(&'a self, path: &str) -> Boo<'a> { /* */ }
}
Run Code Online (Sandbox Code Playgroud)
至
impl<'a> Foo<'a> {
fn foo(&self, path: &str) -> Boo { /* */ }
}
Run Code Online (Sandbox Code Playgroud)
根据我的理解,这没有任何意义,因为我认为第二个版本与第一个使用了生命周期省略的版本完全相同。
如果我们为该方法引入了新的生命周期,那么根据nomicon的此示例似乎就是这种情况。
fn get_mut(&mut self) -> &mut T; // elided
fn get_mut<'a>(&'a mut self) -> &'a mut T; // expanded
Run Code Online (Sandbox Code Playgroud)
那么这和我的第一个代码片段之间有什么区别。
终身'a在fn foo(&'a self, ...) ...为定义impl<'a>,即它是所有相同的foo电话。
寿命'a中fn get_mut<'a>(&'a mut self) ...是为函数来定义。的不同调用get_mut可以具有的不同值'a。
您的密码
Run Code Online (Sandbox Code Playgroud)impl<'a> Foo<'a> { fn foo(&'a self, path: &str) -> Boo<'a> { /* */ } }
不能延长淘汰期。该代码将借用&'a self期限与结构的期限联系起来Foo<'a>。如果Foo<'a>不变'a,那么self只要保持借用'a。
正确延长淘汰寿命是
impl<'a> Foo<'a> {
fn foo<'b>(&'b self, path: &str) -> Boo<'b> { /* */ }
}
Run Code Online (Sandbox Code Playgroud)
该代码不依赖于结构的变化Foo就可以借用self较短的寿命。
变异和不变结构之间差异的示例。
use std::cell::Cell;
struct Variant<'a>(&'a u32);
struct Invariant<'a>(Cell<&'a u32>);
impl<'a> Variant<'a> {
fn foo(&'a self) -> &'a u32 {
self.0
}
}
impl<'a> Invariant<'a> {
fn foo(&'a self) -> &'a u32 {
self.0.get()
}
}
fn main() {
let val = 0;
let mut variant = Variant(&val);// variant: Variant<'long>
let mut invariant = Invariant(Cell::new(&val));// invariant: Invariant<'long>
{
let r = variant.foo();
// Pseudocode to explain what happens here
// let r: &'short u32 = Variant::<'short>::foo(&'short variant);
// Borrow of `variant` ends here, as it was borrowed for `'short` lifetime
// Compiler can do this conversion, because `Variant<'long>` is
// subtype of Variant<'short> and `&T` is variant over `T`
// thus `variant` of type `Variant<'long>` can be passed into the function
// Variant::<'short>::foo(&'short Variant<'short>)
}
// variant is not borrowed here
variant = Variant(&val);
{
let r = invariant.foo();
// compiler can't shorten lifetime of `Invariant`
// thus `invariant` is borrowed for `'long` lifetime
}
// Error. invariant is still borrowed here
//invariant = Invariant(Cell::new(&val));
}
Run Code Online (Sandbox Code Playgroud)