In Rust, one of the most fascinating (and sometimes head-scratching) features is how closures capture variables from their environment—especially wh

From Scope to Thread: Mastering Closure Variable Captures in Rust

submited by
Style Pass
2025-01-23 12:00:09

In Rust, one of the most fascinating (and sometimes head-scratching) features is how closures capture variables from their environment—especially when you involve threads. If you’ve ever tried to spawn a new thread and pass data into the closure without using move, you’ve likely been greeted by the compiler with a wall of text about lifetimes, borrowing, and ownership.

In this blog, we will explore the why and how of capturing variables inside a closure running in a new thread. We’ll start with a simple example that fails to compile, examine why that is, and then fix it step by step. Along the way, we’ll discuss key Rust concepts like ownership, borrowing, Send, Sync, and why they matter so much for concurrency.

You might think this is perfectly reasonable: we have a message string, we spawn a new thread and print the message inside our closure. But Rust’s compiler has a different opinion:

In other words, if the main thread exits before the spawned thread prints message, we end up with a reference to memory that no longer exists.

Leave a Comment