我正在学习官方的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>>`很奇怪,而且我不认为我做对了...我的意思是我想要一个包含对`Item`的引用的`Vec`,并且只要其中包含的对`Item`的引用本身有效,那么这个`Vec`就是有效的。难道不应该是`items: Vec<&'a Item>`吗?
items: Vec<&'a Item>
中,您没有在Item
中指定生命周期参数'a
。编译器在这里不会做任何假设,因此仍然需要指定它。相关问题:https://dev59.com/_FwZ5IYBdhLWcg3wTOzr 和 https://stackoverflow.com/q/43712228/1233251 - E net4