3 ms·
> What does Rust do here? This code results in a compilation error: for v in values { spawn(|| { // Do stuff with v }); }
by kibwen 10y ago
> What does Rust do here?
This code results in a compilation error:
for v in values {
spawn(|| {
// Do stuff with v
});
}
Error output as follows:
error[E0373]: closure may outlive the current function, but it borrows `v`, which is owned by the current function
--> <anon>:7:15
|
7 | spawn(|| {
| ^^ may outlive borrowed value `v`
8 | v;
| - `v` is borrowed here
|
help: to force the closure to take ownership of `v` (and any other referenced variables), use the `move` keyword, as shown:
| spawn(move || {
You can play with the code here: https://is.gd/f4guCw https://is.gd/f4guCw
As the error message says, the real problem with this code, given Rust's semantics, is that the closures are being given pointers to memory that might not be valid by the time the closure gets around to executing (unlike in Go (or any other GC'd lang), the mere existence of a pointer is not enough to keep memory alive). And as the help text at the bottom of the error message describes, one solution is to have the closures themselves assume ownership of the data via the `move` keyword on closures.
- lobster_johnson 10y agoExcellent, thanks. Great error message.
- isaacremuant 10y agoGo might have some complex concepts initially and be a big language but its error messages are impressively helpful and precise. I'm very thankful to that level of dedication.
- kibwen 10y agoThe error message above was from Rust, not Go, is that what you meant? :P