Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does this closure satisfy the trait bounds when it appears to drop a parameter

Hi I am looking over the documentation of asnyc_task and notice that in the example code:

use async_task::Runnable;
use flume::{Receiver, Sender};
use std::rc::Rc;

thread_local! {
    // A queue that holds scheduled tasks.
    static QUEUE: (Sender<Runnable>, Receiver<Runnable>) = flume::unbounded();
}

// Make a non-Send future.
let msg: Rc<str> = "Hello, world!".into();
let future = async move {
    println!("{}", msg);
};

// A function that schedules the task when it gets woken up.
let s = QUEUE.with(|(s, _)| s.clone());
let schedule = move |runnable| s.send(runnable).unwrap();

// Create a task with the future and the schedule function.
let (runnable, task) = async_task::spawn_local(future, schedule);

When it comes to the function signature for ::spawn_local(...) there is a trait bound on Schedule

pub fn spawn_local<F, S>(future: F, schedule: S) -> (Runnable, Task<F::Output>)
where
    F: Future + 'static,
    F::Output: 'static,
    S: Schedule + Send + Sync + 'static,

Where Schedule is the following trait:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

pub trait Schedule<M = ()>: Sealed<M> {
    // Required method
    fn schedule(&self, runnable: Runnable<M>, info: ScheduleInfo);
}

It appears to me that the following code drops info: ScheduleInfo as an argument and so I am wondering how this trait bound is satisfied.

let schedule = move |runnable| s.send(runnable).unwrap();

>Solution :

There is an implementation for Schedule for all Fn(Runnable) that looks like this:

impl<M, F> Schedule<M> for F
where
    F: Fn(Runnable<M>),
{
    fn schedule(&self, runnable: Runnable<M>, _: ScheduleInfo) {
        self(runnable)
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading