Countdown over time

I would like to write code like the following:

struct Foo {
    foo: usize
}

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

But this will not work without receiving invalid lifetime name: 'self is no longer a special lifetime.

How to return a link that lives as long as the object itself?

+4
source share
2 answers

You don’t want the link to display exactly as much as the object. You just need to borrow on the object (perhaps shorter than the whole lifetime of the object), and you want the resulting link to have the lifetime of this borrowing. It is written like this:

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

In addition, the elite of life makes the signature more beautiful:

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

In your example, the lifetime selfis equal 'a, so the lifetime of the returned link should be 'a:

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

( ) , :

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

+10

Source: https://habr.com/ru/post/1599759/


All Articles