I\'ve implemented a struct
which has a list of crontab entries, each of which knows its own recurrence (such as */5 * * * *
in crontab):
As described in Is there any way to return a reference to a variable created in a function?, you cannot create a value in a function and return a reference to it. Nothing would own the result of your iterator chain, thus the reference would point at invalid data.
That doesn't even really matter: as pointed out in the comments, you cannot call into_iter
on self.entries
because you cannot move out of borrowed content to start with, as described in Cannot move out of borrowed content. This means that we cannot have an owned value of an Entry
as the result of the iterator chain to start with.
Crontab
owns the Entry
; as soon as the Crontab
moves, any reference to any Entry
becomes invalid. This means that any references need to be tied to how long self
lives; the generic lifetime 'a
cannot come into play:
fn next_run(&self, from: NaiveDateTime) -> Run {
self.entries
.iter()
.map(|entry| Run {
entry,
datetime: entry.recurrence.next_match(from),
})
.min_by(|this, other| this.datetime.cmp(&other.datetime))
.unwrap()
}
Or the explicit version:
fn next_run<'b>(&'b self, from: NaiveDateTime) -> Run<'b> { /* ... */ }