简体   繁体   English

返回自我生命周期的参考

[英]Return reference with lifetime of self

I'd like to write some code like the following: 我想写一些如下代码:

struct Foo {
    foo: usize
}

impl Foo {
    pub fn get_foo<'a>(&'a self) -> &'self usize {
        &self.foo
    }
}

But this doesn't work, failing with invalid lifetime name: 'self is no longer a special lifetime . 但这不起作用, invalid lifetime name: 'self is no longer a special lifetime

How can I return a reference that lives as long as the object itself? 如何返回与对象本身一样长的引用?

In your example the lifetime of self is 'a so the lifetime of the returned reference should be 'a : 在您的示例中, self的生命周期为'a因此返回引用的生命周期应为'a

pub fn get_foo<'a>(&'a self) -> &'a usize {
    &self.foo
}

However the compiler is able to deduce (lifetime elision) the correct lifetime in simple cases like that, so you can avoid to specify lifetime at all, this way: 但是,编译器能够在这样的简单情况下推断(生命周期缩减)正确的生命周期,因此您可以避免指定生命周期,这样:

pub fn get_foo(&self) -> &usize {
    &self.foo
}

Look here for lifetime elision rules 在这里查看终身省略规则

You don't want the reference to live exactly as long as the object. 您不希望引用与对象完全一样长。 You just want a borrow on the object (quite possibly shorter than the entire lifetime of the object), and you want the resulting reference to have the lifetime of that borrow. 你只是想要对象(相当比对象的整个生命周期较短的可能)上位,并希望最终的参考,以有借的寿命。 That's written like this: 这是这样写的:

pub fn get_foo<'a>(&'a self) -> &'a usize {
    &self.foo
}

Additionally, lifetime elision makes the signature prettier: 此外,终身省略使签名更漂亮:

pub fn get_foo(&self) -> &usize {
    &self.foo
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM