I've got some trouble with replacing function with equivalent closure, compiler complaining
cannot infer an appropriate lifetime due to conflicting requirements
note: ...so that the types are compatible:
expected &std::collections::BTreeSet<&str>
found &std::collections::BTreeSet<&str> rustc(E0495)
in the closure, at the range
method in r.extend(s.range(lower..=upper));
.
But i can't figure out how to put lifetime hint in a closure, and maybe, it's not possible.
use std::collections::BTreeSet;
fn main() {
let mut set = BTreeSet::new();
set.insert("TEST1");
set.insert("TEST3");
set.insert("TEST4");
set.insert("TEST2");
set.insert("TEST5");
println!("init: {:?}", set);
let closure = |lower, upper| {
|s: &BTreeSet<&str>| {
let mut r = BTreeSet::new();
r.extend(s.range(lower..=upper));
r
}
};
set = extract_fn("TEST2", "TEST5")(&set);
set = closure("TEST3", "TEST4")(&set);
println!("result: {:?}", set);
}
fn extract_fn<'a>(
lower: &'a str,
upper: &'a str,
) -> impl Fn(&BTreeSet<&'a str>) -> BTreeSet<&'a str> {
move |s| {
let mut r = BTreeSet::new();
r.extend(s.range(lower..=upper));
r
}
}
Except putting static
lifetime, should a closure with this type of error be transformed to a function ?