Closures and Self and Lifetimes

⚓ Rust    📅 2025-09-05    👤 surdeus    👁️ 3      

surdeus

pub trait Waker {
    fn wake(&self);
}

pub struct LocalWaker(pub Box<dyn Fn()>);

impl Waker for LocalWaker {
    fn wake(&self) {
        self.0()
    }
}
use crate::{future::Future, handler::SocketHandler, waker::LocalWaker};

trait Scheduler {
    type Future: Future;
    fn spawn(&mut self, task: Self::Future);
    fn run(&mut self);
}

struct LocalScheduler {
    runnable: Vec<Box<dyn Future<Waker = LocalWaker>>>,
    updated: Vec<Box<dyn Future<Waker = LocalWaker>>>,
}

impl Scheduler for LocalScheduler {
    type Future = SocketHandler;

    fn spawn(&mut self, task: Self::Future) {
        self.runnable.push(Box::new(task));
    }

    fn run(&mut self) {
        // for all the futures in runnable poll them
        // then wait on the reactor to update
        self.runnable.append(&mut self.updated);
        for run in self.runnable.drain(..) {
            run.poll(LocalWaker(Box::new(|| self.updated.push(run))))
        }
    }
}

Very new to rust - trying to figure out what is the right way to have a closure contain self. I think I understand the issue here:
Rust is complaining that the reference to self in the closure might not be valid because rust does not know exactly what the lifetime of self could be.
But how do I specify that the lifetime of the struct will be longer than the lifetime of the reference to self in the closure?

1 post - 1 participant

Read full topic

🏷️ Rust_feed