I'm writing a simple server that handles commands.
The original implementation was
struct Server<T, F>
where
F: for<'a> AsyncFn4<
&'a mut T,
&'a str,
&'a UdpSocket,
&'a SocketAddr,
Output = Result<()>,
{
context: T,
socket: UdpSocket,
handler: F,
}
...
// main loop pub async fn run(mut self)
let res = (self.handler)(&mut self.context, msg, &self.socket, origin).await;
Now I want to spawn a new task when I receive a message. And I want to modify the server such that
pub struct Context<T> {
pub data: Arc<Mutex<T>>,
pub socket: Arc<UdpSocket>,
pub origin: SocketAddr,
}
pub struct Server<T, F>
where
F: for<'a> AsyncFn2<
&'a Context<T>,
&'a str,
Output = Result<()>,
{
data: Arc<Mutex<T>>,
socket: Arc<UdpSocket>,
handler: F,
}
...
// main loop
tokio::spawn(async {
let context = Context {
data: self.data.clone(),
socket: self.socket.clone(),
origin,
};
let res = (self.handler)(&context, msg).await;
});
This however errors out.
future cannot be sent between threads safely
withinimpl Future<Output = ()>, the traitSendis not implemented for<F as AsyncFn2<&Context<T>, &str>>::OutputFuture
And it seems no matter how I try to specifySend, it still fails.