返回带有自我生存期的参考 [英] Return reference with lifetime of self

查看:52
本文介绍了返回带有自我生存期的参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写如下代码:

struct Foo {
    foo: usize
}

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

但是这不起作用,失败的原因是invalid lifetime name: 'self is no longer a special lifetime.

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?

推荐答案

您不希望引用的寿命与对象的寿命一样长.您只想在对象上 a 借用(可能比对象的整个生存期短),并且希望结果引用具有该借用的生存期.是这样写的:

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
}

这篇关于返回带有自我生存期的参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆