Understanding Rust Closures

antoine.vandecreme.net

39 points by avandecreme 9 hours ago


- 35 minutes ago
[deleted]
andy_xor_andrew - 5 hours ago

if I'm not mistaken (and I very well may be!) my primary confusion with closures comes from the fact that: the trait they implement (FnOnce / Fn / FnMut) depends entirely upon what happens inside the closure.

It will automatically implement the most general, relaxed version (FnMut I think?) and only restrict itself further to FnOnce and Fn based on what you do inside the closure.

So, it can be tricky to know what's going on, and making a code change can change the contract of the closure and therefore where and how it can be used.

(I invite rust experts to correct me if any of the above is mistaken - I always forget the order of precedence for FnOnce/Fn/FnMut and which implies which)

Sytten - 2 hours ago

And now we have the Async version of each of those, which makes me very happy and reduces the shenanigans and lifetime issues.

Also worthy of note is that there is talk to add a syntax for explicit captures.

amelius - 6 hours ago

Closures are the bread and butter of functional programming, but Rust made closures a complicated mess.