Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make function generics less restrictive #17

Merged

Conversation

marcospb19
Copy link
Contributor

From the documentation of FnMut:

Since FnOnce is a supertrait of FnMut, any instance of FnMut can be used where a FnOnce is expected, and since Fn is a subtrait of FnMut, any instance of Fn can be used where FnMut is expected.

And from the docs of Fn:

Use Fn as a bound when you want to accept a parameter of function-like type and need to call it repeatedly and without mutating state (e.g., when calling it concurrently). If you do not need such strict requirements, use FnMut or FnOnce as bounds.

Basically Fn is more restrictive, and if you don't need the restrictions, you should go with FnMut or FnOnce.

Here's a real example where Fn instead of FnMut generated an slightly more complicated code:

use std::cell::RefCell;

let a = RefCell::new(Vec::new());

sevenz_rust::decompress_file_with_extract_fn(archive_path, ".", |entry, _, _| {
    let name = entry.name().to_string();
    a.borrow_mut().push(name);
    Ok(true)
})

By replacing Fn by FnMut:

let a = Vec::new(); // simplified here

sevenz_rust::decompress_file_with_extract_fn(archive_path, ".", |entry, _, _| {
    let name = entry.name().to_string();
    a.push(name); // simplified here
    Ok(true)
})

by replacing `Fn` by `FnMut` where allowed
@dyz1990 dyz1990 merged commit e451b2f into dyz1990:main Apr 18, 2023
3 checks passed
@marcospb19 marcospb19 deleted the make-functions-types-less-restrictive branch April 18, 2023 15:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants