特征的生命周期

发布于 2025-01-09 08:38:15 字数 801 浏览 4 评论 0原文

假设有一些结构:

struct ResourceData { }

我们可以创建它的列表:

pub struct ResourceList
{
    pub v: Vec<ResourceData>,
}

但是如果我添加一个间接级别:

pub trait Resource<'a> {
    fn data(&self) -> &'a ResourceData;
    fn data_mut(&mut self) -> &'a mut ResourceData;
}

那么我会很混乱:

pub struct ResourceList2<R: Resource<'a>> // What should be 'a?
{
    pub v: Vec<R>,
}

'a应该是什么?

'a 可能是向量的生命周期,但如果删除一个元素,引用的生命周期就会缩短,因为引用会中断。因此,根据我的理解, 'a 不是向量的生命周期。

Let there is some struct:

struct ResourceData { }

We can create its list:

pub struct ResourceList
{
    pub v: Vec<ResourceData>,
}

but if I add a level of indirection:

pub trait Resource<'a> {
    fn data(&self) -> &'a ResourceData;
    fn data_mut(&mut self) -> &'a mut ResourceData;
}

then I am messed:

pub struct ResourceList2<R: Resource<'a>> // What should be 'a?
{
    pub v: Vec<R>,
}

What should be 'a?

'a could be the lifetime of the vector, but if an element is removed, the lifetime of the references shorten, because references break. So, accordingly my understanding, 'a isn't the lifetime of the vector.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

嗫嚅 2025-01-16 08:38:15

资源不应该有生命周期参数,而应该使用省略的生命周期:

pub trait Resource {
    fn position(&self) -> &ResourceData;
    fn position_mut(&mut self) -> &mut ResourceData;
}

理解这一点后,问题就消失了,只是:

pub struct ResourceList2<R: Resource> // What should be 'a?
{
    pub v: Vec<R>,
}

Resource should not have a lifetime argument, but instead just use elided lifetimes:

pub trait Resource {
    fn position(&self) -> &ResourceData;
    fn position_mut(&mut self) -> &mut ResourceData;
}

After understanding this, the question disappears, just:

pub struct ResourceList2<R: Resource> // What should be 'a?
{
    pub v: Vec<R>,
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文