Imagine you want to make an object that constructs s closure and becomes its owner, so that it can issue handles to it, this is MWE I managed to make:
struct A<'a>
{
data: &'a usize,
function: Box<dyn Fn(&usize) -> usize>,
b: B<'a>
}
struct B<'a>
{
f: &'a dyn Fn(&usize) -> usize
}
impl<'a> A<'a>
{
pub fn new(data: &'a usize) -> A<'a>
{
let closure = Box::new(|i : &usize| {*i});
Self
{
data,
function: closure,
b: B{f: closure.as_ref()}
}
}
}
Rust doesn't like this:
error[E0515]: cannot return value referencing local variable
closure``
But in principle this should be fine. B
is a field of A
and will live for the exact same amount as A
in all instantiations. So B
can borrow data from A
with no risk.
The reason this is a problem is that rust has no true concept of a constructor. As far as it is concerned, closure
exists only in the scope of the new
, even though the whole point is to shove it into A
. The BC thus is incapable of proving correctness, even though this is a very sane use of references in this specific context.
For example this will compile:
struct A<'a>
{
data: &'a usize,
function: Box<dyn Fn(&usize) -> usize>,
b: B<'a>
}
struct B<'a>
{
f: &'a dyn Fn(&usize) -> usize
}
impl<'a> A<'a>
{
pub fn new(data: &'a usize)
{
let closure = Box::new(|i : &usize| {*i});
let b = B{f: closure.as_ref()};
}
}
which is essentially the same idea. What can I do here?