Return reference with lifetime of self

前提是你 提交于 2020-01-23 07:59:06

问题


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.

How can I return a reference that lives as long as the object itself?


回答1:


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
}



回答2:


In your example the lifetime of self is 'a so the lifetime of the returned reference should be '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



来源:https://stackoverflow.com/questions/31641610/return-reference-with-lifetime-of-self

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!