From 5c0abab1b7bf0f2858c451d6f0efc7ca0e138fc6 Mon Sep 17 00:00:00 2001 From: hozan23 Date: Sat, 29 Jun 2024 21:16:46 +0200 Subject: use shadown variables to name clones and place them between {} when spawning new tasks --- p2p/examples/chat.rs | 42 +++++++++++++++++++++++------------------- 1 file changed, 23 insertions(+), 19 deletions(-) (limited to 'p2p/examples') diff --git a/p2p/examples/chat.rs b/p2p/examples/chat.rs index 4dd87c5..1ad215c 100644 --- a/p2p/examples/chat.rs +++ b/p2p/examples/chat.rs @@ -59,14 +59,16 @@ impl ChatProtocol { #[async_trait] impl Protocol for ChatProtocol { async fn start(self: Arc) -> Result<(), Error> { - let selfc = self.clone(); let stdin = io::stdin(); - let task = self.executor.spawn(async move { - loop { - let mut input = String::new(); - stdin.read_line(&mut input).await.unwrap(); - let msg = format!("> {}: {}", selfc.username, input.trim()); - selfc.peer.broadcast(&Self::id(), &msg).await; + let task = self.executor.spawn({ + let this = self.clone(); + async move { + loop { + let mut input = String::new(); + stdin.read_line(&mut input).await.unwrap(); + let msg = format!("> {}: {}", this.username, input.trim()); + this.peer.broadcast(&Self::id(), &msg).await; + } } }); @@ -126,23 +128,25 @@ fn main() { let handle = move || ctrlc_s.try_send(()).unwrap(); ctrlc::set_handler(handle).unwrap(); - let ex_cloned = ex.clone(); run_executor( - async { - let username = cli.username; + { + let ex = ex.clone(); + async { + let username = cli.username; - // Attach the ChatProtocol - let c = move |peer| ChatProtocol::new(&username, peer, ex_cloned.clone().into()); - backend.attach_protocol::(c).await.unwrap(); + // Attach the ChatProtocol + let c = move |peer| ChatProtocol::new(&username, peer, ex.clone().into()); + backend.attach_protocol::(c).await.unwrap(); - // Run the backend - backend.run().await.unwrap(); + // Run the backend + backend.run().await.unwrap(); - // Wait for ctrlc signal - ctrlc_r.recv().await.unwrap(); + // Wait for ctrlc signal + ctrlc_r.recv().await.unwrap(); - // Shutdown the backend - backend.shutdown().await; + // Shutdown the backend + backend.shutdown().await; + } }, ex, ); -- cgit v1.2.3