(1) doesn't work because filter() gives the callback only a reference, &T, so the type of x should be &&mut u8.
As for (2), this is really interesting - I was able to reduce it to the following:
|x: &'_ mut u8| -> &'_ mut u8 { x };
And the compiler complains
error: lifetime may not live long enough
--> src/main.rs:2:37
|
2 | |x: &'_ mut u8| -> &'_ mut u8 { x };
| - - ^ returning this value requires that `'1` must outlive `'2`
| | |
| | let's call the lifetime of this reference `'2`
| let's call the lifetime of this reference `'1`
fn main() {
let mut b = vec![1,2,3];
let c: Vec<&mut u8> = b.iter_mut()
.filter_map(|x| {
(|x| Some(x))(x)
})
.collect(); // 2 have lifetime issue
}
I put it in a Vec c just to show that it is indeed a collection of mutable references, but you can pick any compatible collection you like.
(I don't think there is) really a way to make this work without putting the original collection b into a variable because its lifetime ends when it goes out of scope (even though iter_mut is by reference, the vec is no longer in scope after that in the original example)
It might not be possible due to the use of a closure and not a function. I don't know why it's necessary to do it because the original post provides no specifics, but perhaps start there.