DEV Community

El Bruno for Microsoft Azure

Posted on • Originally published at elbruno.com on

#Rust πŸ¦€ – Accesing external vars in threads 🧡

Hi !

In order to access external variables in a thread, we must use the move closure with the move keyword in the thread creation.

In example, these 2 lines will define and create a mutable variable and then a new thread where we can access the var.


let mut new_var = "hey!";
let handle =thread::spawn(move || {
// access to new_var here
})

Enter fullscreen mode Exit fullscreen mode

And an example of the previous code will have:

  • A main thread where we declare a string var with a message.
  • The 2nd thread that will display a message using the main thread message.

The code output shows that the app is closed before finishing the execution of the 2nd thread.

Run outuput with the message from the 2nd thread using a var from the main thread

Super cool !

Happy coding!

Greetings

El Bruno

More posts in my blog ElBruno.com.


Top comments (0)