1
0
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:
Chayim Refael Friedman 2023-12-15 17:22:59 +02:00 committed by GitHub
parent 97a47cab78
commit 61f3e5fb51
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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.