I have a function that takes array of posts and an optional after_id
to skip posts with an id less or equal to given.
fn get_page<'a>(data: &'a Vec<u64>, after_id: Option<u64>) -> Vec<&u64> {
let data = data.iter();
let data = match after_id {
Some(id) => data.skip_while(|&&post| post <= id),
None => data,
};
data.take(10).collect()
}
This code triggers a compilation error, stating that Some
arm creates a iter::SkipWhile
struct and its type is incompatible with posts
type (slice::Iter
) from None
arm.
The only fix I see, without deconstructing match
into if
s or something like that, is:
let posts = match after_id {
Some(id) => posts.skip_while(|post| post.id <= id).collect(),
None => posts.collect(),
};
The obvious downside is that I needlessly iterate whole collection and use extra memory.
Is it possible to apply skip_while
conditionally and store the result in a single variable, without collect
ing an intermediate result?