3 ms·
In the article they discuss that Rust closures are just sugar for structs that work exactly as you describe. As with any other syntactic sugar, it's easy to re
by wffurr 7y ago
In the article they discuss that Rust closures are just sugar for structs that work exactly as you describe.
As with any other syntactic sugar, it's easy to reason about the behavior once you know what the syntax desugars into.
One classic example I see with beginning programmers all the time is the order of the parts of a for loop.
e.g.
for(initialization statement; bounds check expression; increment statement) {
...
}
is just syntactic sugar for:
{
initialization statement;
while (bounds check expression) {
...
increment statement;
}
}
But once you understand what a for-loop desugars into, it's trivial to use and reason about.
Closures aren't much different. In Rust, if anything, they're less magic, because you have to be explicit about the lifetime of the closure relative to the references it's borrowing.
- cesarb 7y ago> is just syntactic sugar for [...] There's just a subtle detail to keep in mind here: both "continue" and "break" are syntactic sugar for "goto", and when converting a "for" loop into a "while" loop, you have to also convert "continue" to a "goto" to a label just before the increment statement.