Understanding Rust Closures
Posted by avandecreme 7 hours ago
Comments
Comment by andy_xor_andrew 3 hours ago
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)
Comment by yoshuaw 2 hours ago
The way I remember the ordering is by thinking about the restrictions the various Fn traits provide from a caller's perspective:
1. FnOnce can only ever be called once and cannot be called concurrently. This is the most restrictive.
2. FnMut can be called multiple times but cannot be called concurrently. This is less restrictive than FnOnce.
3. Fn can be called multiple times and can even be called concurrently. This is the least restrictive.
So going from most to least restrictive gives you `FnMut: FnOnce` and `Fn: FnMut`.Comment by umanwizard 2 hours ago
It’s more precise to say that Fn can be called even when you only have shared access to it, which is a necessary, but not sufficient, condition for being able to be called concurrently.
Comment by krukah 1 hour ago
FnOnce
FnMut
Fn
Comment by KolmogorovComp 2 hours ago
Comment by gpm 10 minutes ago
Comment by umanwizard 2 hours ago
The least restrictive for the function itself is the opposite order: FnOnce (it can do anything to its environment, including possibly consuming things without putting them back into a consistent state), followed by FnMut (it has exclusive access to its environment, and so is allowed to mutate it, but not destroy it), followed by Fn (it has only shared access to its environment and therefore is not allowed to mutate it).
Since these orders are inverses of each other, functions that are easier to write are harder to call and vice versa. That’s why they implement the trait with the minimum amount of power possible, so that they can be called in more places.
Comment by Sytten 14 minutes ago
Also worthy of note is that there is talk to add a syntax for explicit captures.
Comment by amelius 4 hours ago
Comment by openuntil3am 3 hours ago
Comment by Klonoar 4 hours ago
In fact I can’t remember the last time I had to fight with them.
Comment by convolvatron 3 hours ago
Comment by kibwen 2 hours ago
The comment above isn't saying that closures are trivial. Once you understand the borrow checker, you understand that it's a miracle that closures in Rust can possibly work at all, given Rust's other dueling goals of being a GC-less language with guaranteed memory safety despite letting closures close over arbitrary references. Rust is in uncharted territory here, drawing the map as it goes.
Comment by speed_spread 1 hour ago
Comment by ordu 2 hours ago