I would like to send a closure via channels:
use std::thread;
use std::sync::mpsc;
#[derive(Debug)]
struct Test {
s1: String,
s2: String,
}
fn main() {
let t = Test {
s1: "Hello".to_string(),
s2: "Hello".to_string(),
};
let (tx, rx) = mpsc::channel::<FnOnce(&mut Test)>();
thread::spawn(move || {
let mut test = t;
let f = rx.recv().unwrap();
f(&mut test);
println!("{:?}", test);
});
tx.send(move |t: &mut Test| {
let s = "test".to_string();
t.s1 = s;
});
}
I get a bunch of errors:
error[E0277]: the trait bound `for<'r> std::ops::FnOnce(&'r mut Test): std::marker::Sized` is not satisfied
--> src/main.rs:15:20
|
15 | let (tx, rx) = mpsc::channel::<FnOnce(&mut Test)>();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `for<'r> std::ops::FnOnce(&'r mut Test)` does not have a constant size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `for<'r> std::ops::FnOnce(&'r mut Test)`
= note: required by `std::sync::mpsc::channel`
error[E0277]: the trait bound `for<'r> std::ops::FnOnce(&'r mut Test): std::marker::Sized` is not satisfied
--> src/main.rs:15:20
|
15 | let (tx, rx) = mpsc::channel::<FnOnce(&mut Test)>();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `for<'r> std::ops::FnOnce(&'r mut Test)` does not have a constant size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `for<'r> std::ops::FnOnce(&'r mut Test)`
= note: required by `std::sync::mpsc::Sender`
error[E0599]: no method named `recv` found for type `std::sync::mpsc::Receiver<for<'r> std::ops::FnOnce(&'r mut Test)>` in the current scope
--> src/main.rs:18:20
|
18 | let f = rx.recv().unwrap();
| ^^^^
|
= note: the method `recv` exists but the following trait bounds were not satisfied:
`for<'r> std::ops::FnOnce(&'r mut Test) : std::marker::Sized`
error[E0599]: no method named `send` found for type `std::sync::mpsc::Sender<for<'r> std::ops::FnOnce(&'r mut Test)>` in the current scope
--> src/main.rs:22:8
|
22 | tx.send(move |t: &mut Test| {
| ^^^^
|
= note: the method `send` exists but the following trait bounds were not satisfied:
`for<'r> std::ops::FnOnce(&'r mut Test) : std::marker::Sized`
It seems that FnOnce
is not sendable but I don't understand why.