Vec中的Rust生命周期:语法错综复杂

问题描述 投票:1回答:1

我正在通过官方书籍学习Rust。我在程序中遇到了一个奇怪的语法:

pub struct Shelf<'a> {
    items: Vec<&'a Item<'a>>, // => working as expected
    //items: Vec<Item<'a>>, // => not working
    //items: Vec<&'a Item>, // => not working
}

Item是一个包含对其他类型的引用的结构:

pub struct Item<'a> {
    owner: &'a Owner,
    name: String,
    avg_rating: u32,
    status: ItemStatus,
}

pub struct Owner {
    pub name: String,
}

在我看来,语法items: Vec<&'a Item<'a>>是奇怪的,我不认为我做得对...我想要的是一个包含对Vecs的引用的Item,并且Vec是有效的,只要它包含对Items的引用本身是有效的。不应该是items: Vec<&'a Item>而不是?

rust lifetime
1个回答
3
投票

您需要指定两个生命周期:

  • 您的矢量包含对项目的引用。
  • 每个项目都包含对其所有者的引用。

您需要指定每种类型的引用存在多长时间。如果您编写Vec<&'a Item<'b>>,则第一个生命周期('a)指定对项目的引用生存时间,第二个生命周期('b)指定对所有者的引用生存时间。

当您编写Vec<Item<'a>>时,编译器不知道项目存在多长时间。

当你编写Vec<&a Item>时,编译器不知道所有者有多长时间。

当您对两个点(Vec<&'a Item<'a>>)使用相同的生命周期时,您告诉编译器两个生命周期都是相同的,这意味着项目必须与其所有者一样长。这可能过于严格,根据您的使用情况,告诉编译器项目可能不会比其所有者活得更久可能更好:

pub struct Shelf<'a, 'b: 'a> {
    items: Vec<&'b Item<'a>>,
}
© www.soinside.com 2019 - 2024. All rights reserved.