特征的生命周期
假设有一些结构:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
资源不应该有生命周期参数,而应该使用省略的生命周期:
理解这一点后,问题就消失了,只是:
Resource should not have a lifetime argument, but instead just use elided lifetimes:
After understanding this, the question disappears, just: