【发布时间】:2019-03-04 14:10:15
【问题描述】:
我正在通过官方书籍学习 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>> 的语法很奇怪,我认为我做的不对...我想要的是一个包含对 Items 的引用的 Vec,以及 @987654328只要它包含的对Items 的引用本身是有效的,@ 就有效。不应该是items: Vec<&'a Item>吗?
【问题讨论】:
-
在
items: Vec<&'a Item>中,您没有在Item中指定生命周期参数'a。编译器不会在这里做任何假设,所以你仍然需要指定它。相关问题:stackoverflow.com/q/31609137/1233251和stackoverflow.com/q/43712228/1233251