I am trying to compile the following code (playground):
trait MockFutureTrait {
type Item;
}
struct MockFuture<T> {
item: T,
}
impl<T> MockFutureTrait for MockFuture<T> {
type Item = T;
}
struct FragMsgReceiver<'a, 'c: 'a> {
recv_dgram: &'a FnMut(&mut [u8])
-> Box<MockFutureTrait<Item = &mut [u8]> + 'c>,
}
fn constrain_handler<F>(f: F) -> F
where
F: FnMut(&mut [u8]) -> Box<MockFutureTrait<Item = &mut [u8]>>,
{
f
}
fn main() {
let mut recv_dgram = constrain_handler(|buf: &mut [u8]| {
Box::new(MockFuture { item: buf }) as Box<MockFutureTrait<Item = &mut [u8]>>
});
let ref_recv_dgram = &mut recv_dgram;
let fmr = FragMsgReceiver {
recv_dgram: ref_recv_dgram,
};
}
And I get the compile error:
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/main.rs:28:37
|
28 | Box::new(MockFuture { item: buf }) as Box<MockFutureTrait<Item = &mut [u8]>>
| ^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #2 defined on the body at 27:44...
--> src/main.rs:27:44
|
27 | let mut recv_dgram = constrain_handler(|buf: &mut [u8]| {
| ____________________________________________^
28 | | Box::new(MockFuture { item: buf }) as Box<MockFutureTrait<Item = &mut [u8]>>
29 | | });
| |_____^
note: ...so that expression is assignable (expected &mut [u8], found &mut [u8])
--> src/main.rs:28:37
|
28 | Box::new(MockFuture { item: buf }) as Box<MockFutureTrait<Item = &mut [u8]>>
| ^^^
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that expression is assignable (expected std::boxed::Box<MockFutureTrait<Item=&mut [u8]> + 'static>, found std::boxed::Box<MockFutureTrait<Item=&mut [u8]>>)
--> src/main.rs:28:9
|
28 | Box::new(MockFuture { item: buf }) as Box<MockFutureTrait<Item = &mut [u8]>>
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
I tried to add various lifetime hints, but I couldn't get this code to compile.
My previous related questions on SO about this:
Cannot infer a lifetime for a struct containing a reference to a closure: Solving the same problem, when the return value is a simple struct and not a trait.
How can multiple struct fields be generics that use the same higher-kinded lifetime?: About trying to solve this problem without Boxes. The answer suggests that for now I will have to use Box>.
Note that I am using the helper function constrain_handler
according to a suggestion I got in question 2; it allows me to overcome a different compilation error.