Scoped closures for owned structs

⚓ rust    📅 2025-06-17    👤 surdeus    đŸ‘ī¸ 3      

surdeus

This is not a real problem that I have, but I was thinking on how similar functionality can be implemented in Rust.

I have an application struct, which owns other subsystems, such as the Executor. I want to be able to push closures to the executor, which contain references to the application struct. Essentially I want to have my own scoped closures, similar to scoped threads in std. As in the following example.

What are the safe ways to implement this? I want the App to specifically not be wrapped in Rc.
Also I know that this implementation has a flaw that std::mem::swap can, in theory, be abused, to replace the executor with another one, which will take away ownership from the App, also Executor can move the closures somewhere, which will also result in access-after-free.

struct App(RefCell<AppInner>);

struct AppInner {
    executor: Executor,
    ...
}

struct Executor {
    queue: Vec<Box<dyn FnOnce()>>,
    ...
}

impl App {
    fn on_startup(&self) {
        // SAFETY: The executor is owned by the application and is dropped
        // before the `Application` is destroyed. `RefCell` ensures that mutable
        // aliasing will not happen.
        let this: &'static Self = unsafe { std::mem::transmute(self) };
        self.borrow_mut().executor.push_task(|| this.notify_pause());
    }

    fn notify_pause(&self) { ... } 
}

impl Executor {
    fn push_task(&mut self, task: impl FnOnce()) { ... }
}

And even if I am working with Rc, I wonder whether there a way to go from &Self to Rc<Self> in the on_startup function, similar to how shared_from_this is working in C++. I've seen this discussed here[1], but wouldn't mind hearing more thoughts about this.


  1. https://stackoverflow.com/a/79259201 â†Šī¸Ž

1 post - 1 participant

Read full topic

đŸˇī¸ rust_feed