Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

what does it mean for FnMut to take an immutable reference?

pub fn sort_by_key<K, F>(&mut self, mut f: F)
where
    F: FnMut(&T) -> K,
    K: Ord,
{
    merge_sort(self, |a, b| f(a).lt(&f(b)));
}

Here FnMut takes an immutable reference &T, what does it mean?

Isn’t FnMut supposed to take a mutable reference &mut T?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

No, a FnMut means this function may use a mutable reference to a caputred variable. For example, take this function:

let mut x = 5;
{
    let mut square_x = || x *= x;
    square_x();
}
assert_eq!(x, 25);

This function takes no arguments. Certainly no immutable arguments. Yet it’s considered a FnMut because it captures the mutable reference to x and mutates. it.

Note that Fn is a subtype of FnMut. Thus, any function that takes a FnMut can also be passed a function that does not mutate state. In this case, |a, b| f(a).lt(&f(b)) is just a Fn. It can be called multiple times and mutates no state. But any Fn is also a valid FnMut and any FnMut or Fn is also a valid FnOnce.

This does mean Fn can take a mutable reference as a parameter, so this is valid:

let b:Box<dyn Fn(&mut u8)->()> = Box::new(|a|*a+=1);

This function uses a mutable reference yet it’s a Fn not a FnMut since it doesn’t capture any variables.

See also this question for a lot more details

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading