Reputation: 3113
I have a struct with a reference in it:
pub struct ScheduledItem<'a> {
pub item: &'a item::Item,
pub timeshift: i32
}
Now I want to write a function which return a Vec of references to this struct:
pub fn items_with_times<'a>(items: &Vec<ScheduledItem>) -> Vec<(u32, &'a ScheduledItem)> {
But what I get is an error:
src/scheduled_item.rs:25:74: 25:87 error: wrong number of lifetime parameters: expected 1, found 0 [E0107]
src/scheduled_item.rs:25 pub fn items_with_times<'a>(items: &Vec<ScheduledItem>) -> Vec<(u32, &'a ScheduledItem)> {
^~~~~~~~~~~~~
Isn't &'a
enough? What's wrong here?
Upvotes: 1
Views: 259
Reputation: 31263
Your struct has a generic lifetime parameter. In Rust you need to specify all generic parameters (e.g. you can't return a Vec
, just a Vec<T>
). So your return type should be Vec<(u32, ScheduledItem<'a>)>
and your argument type should be &[ScheduledItem<'a>]
, since there's no benefit of &Vec<T>
over &[T]
Isn't
&'a
enough?
&'a T
specifies that it's a reference with the lifetime 'a
to a T
, meaning that the object it is pointing to doesn't outlive 'a
.
T<'a>
on the other hand specifies that your T<'a>
type doesn't live longer than 'a
. Which in turn means that any object of that type won't outlive 'a
and that the object cannot contain references to objects that live shorter than 'a
.
Upvotes: 2