I would like to pass a FnOnce
closure to an object to be used later, but I would like to avoid any heap allocation. I can avoid heap allocation by keeping the closure on the stack. But the problem is that I can't pass a reference to the object because the FnOnce
call_once
consumes the closure. So I need to pass an owned pointer (e.g. Box
) without heap allocation.
Is this possible? What I'd like to do is this:
fn main() {
let mut scheduler = NoHeapScheduler();
// allocate the task on the stack
let task = move ||;
// somehow pass ownership of the closure, while keeping it allocated on the stack.
scheduler.add_task(StaticBox::new(task));
schedule.run();
}
As far as I know this should be safe as long as the scheduler doesn't outlive the task. Is there any way to make this happen?