You've already forked comprehensive-rust
mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-06-15 22:00:26 +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:
committed by
GitHub
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`
|
`FnMut` wherever an `FnOnce` is called for, and you can use an `Fn` wherever an `FnMut` or `FnOnce`
|
||||||
is called for.
|
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`),
|
The compiler also infers `Copy` (e.g. for `add_3`) and `Clone` (e.g. `multiply_sum`),
|
||||||
depending on what the closure captures.
|
depending on what the closure captures.
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user