我正在通过官方书籍学习 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>>
很奇怪,我认为我做的不对...我想要的是 Vec
其中包含对 Item
的引用s,那Vec
只要对 Item
的引用有效它包含的内容本身是有效的。不应该是items: Vec<&'a Item>
吗?相反?
最佳答案
您需要指定两个生命周期:
- 您的向量包含对项目的引用。
- 每个项目都包含对其所有者的引用。
您需要指定每种类型的引用的生命周期。如果你写 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>>,
}
关于Vec<&T> : convoluted syntax 中的 Rust 生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54984969/