|
|
|
|
|
by barosl
3742 days ago
|
|
So, for those who may know JavaScript, you may have seen code like this: var closures = [];
for (var i=0;i<5;i++) {
closures.push(function() {
console.log(i);
});
}
The code above will result in incorrect results: 5, 5, 5, 5, 5. Because you're capturing `i` as a reference.To avoid this, JS devs typically do this: closures.push((function(i) {
return function() {
console.log(i);
};
})(i));
Or, if you can afford the ES6 support: for (let i=0;i<5;i++) {
/* `let`-scoped `i`s are created individually at each iteration, so it is safe to capture them by references. */
}
Rust supports this pattern by a built-in syntax. That's what `move` means. If you prepend the `move` keyword before the closure, the variables will be captured by values, not references. |
|
The real cause of confusion is mutation and javascript's scoping rules.