[Rust🦀] How To Pass The Closure To The Function Argument

Rust

For example `execute()` function can take the type of closure as `F`

F defines `FnOnece() + Send + 'static` ('static is lifetime bound)

The following code sends the closure defined as `f` to another thread.

// Recall: Take closure that types are three.
// Fn, FnMut, FnOnce

// Recall: Trait bound: limitation of implementing type
// i.e. <T: Display> is a subset of <T> (<T: Display> は <T>の部分集合)
// pub fn spawn<F, T>(f: F) -> JoinHandle<T>
//     where
// F: FnOnce() -> T,
// F: Send + 'static,
// T: Send + 'static,

pub fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static, {
    let job = Box::new(f);

    self.sender.send(job).unwrap();
}

You can see the details by
https://doc.rust-lang.org/stable/book/ch20-02-multithreaded.html

コメント

タイトルとURLをコピーしました