You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
error[E0373]: closure may outlive the current function, but it borrows `message`, which is owned by the current function
296
+
--> src/main.rs:7:32
297
+
|
298
+
7 |let handle = thread::spawn(|| {
299
+
| ^^ may outlive borrowed value `message`
300
+
8 | println!("{}", message);
301
+
| ------- `message` is borrowed here
302
+
|
303
+
note: functionrequires argument type to outlive `'static`
304
+
--> src/main.rs:7:18
305
+
|
306
+
7 | let handle = thread::spawn(|| {
307
+
| __________________^
308
+
8 | | println!("{}", message);
309
+
9 | | });
310
+
| |______^
311
+
help: to force the closure to take ownership of `message` (and any other referenced variables), use the `move` keyword
312
+
|
313
+
7 | let handle = thread::spawn(move || {
314
+
| ++++
315
+
316
+
For more information about this error, try `rustc --explain E0373`.
317
+
error: could not compile `hello_world` (bin "hello_world") due to 1 previous error
318
+
```
319
+
320
+
____
321
+
322
+
The program in this case fails to compile. Here, Rust will try to borrow the message variable into the separate thread.
323
+
324
+
```bash
325
+
7 | let handle = thread::spawn(|| {
326
+
| ^^ may outlive borrowed value `message`
327
+
```
328
+
329
+
However, Rust doesn't know how long the spawned thread will run. Thus it can't tell if the reference to the `message` variable will always be valid.
330
+
331
+
By adding the `move` keyword before the closure, we force the closure to take ownership of the `message` variable or any variable used inside closure.
332
+
333
+
We are telling Rust that the main thread won't use the `message` variable anymore. This is a classic example of Rust ownership and how it saves us from mishaps. To learn more about ownership in Rust, visit [Rust Ownership](https://www.programiz.com/rust/ownership).
334
+
335
+
Note that moving a value into a thread can be useful for parallelism, but it can also be a source of bugs if not used carefully.
0 commit comments