mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-01-18 20:39:35 +02:00
Add explanation about when you should use each of the Fn*
traits (#1579)
Beginners are confused by this often. --------- Co-authored-by: Dustin J. Mitchell <dustin@v.igoro.us>
This commit is contained in:
parent
97a47cab78
commit
61f3e5fb51
@ -48,6 +48,12 @@ captured values.
|
||||
`FnMut` wherever an `FnOnce` is called for, and you can use an `Fn` wherever an `FnMut` or `FnOnce`
|
||||
is called for.
|
||||
|
||||
When you define a function that takes a closure, you should take `FnOnce` if you can (i.e. you call it once), or `FnMut`
|
||||
else, and last `Fn`. This allows the most flexibility for the caller.
|
||||
|
||||
In contrast, when you have a closure, the most flexible you can have is `Fn` (it can be passed everywhere), then `FnMut`,
|
||||
and lastly `FnOnce`.
|
||||
|
||||
The compiler also infers `Copy` (e.g. for `add_3`) and `Clone` (e.g. `multiply_sum`),
|
||||
depending on what the closure captures.
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user