简体   繁体   中英

What does this Rust Closure argument syntax mean?

I modified code found on the internet to create a function that obtains the statistical mode of any Hashable type that implements Eq, but I do not understand some of the syntax. Here is the function:

use std::hash::Hash;
use std::collections::HashMap;

pub fn mode<'a, I, T>(items: I) -> &'a T 
where I: IntoIterator<Item = &'a T>, 
      T: Hash + Clone + Eq, {
  let mut occurrences: HashMap<&T, usize> = HashMap::new();

  for value in items.into_iter() {
      *occurrences.entry(value).or_insert(0) += 1;
  }

  occurrences
      .into_iter()
      .max_by_key(|&(_, count)| count)
      .map(|(val, _)| val)
      .expect("Cannot compute the mode of zero items")
}

(I think requiring Clone may be overkill.)

The syntax I do not understand is in the closure passed to map_by_key:

|&(_, count)| count

What is the &(_, count) doing? I gather the underscore means I can ignore that parameter. Is this some sort of destructuring of a tuple in a parameter list? Does this make count take the reference of the tuple's second item?

.max_by_key(|&(_, count)| count) is equivalent to .max_by_key(f) where f is this:

fn f<T>(t: &(T, usize)) -> usize {
    (*t).1
}

f() could also be written using pattern matching, like this:

fn f2<T>(&(_, count): &(T, usize)) -> usize {
    count
}

And f2() is much closer to the first closure you're asking about.

The second closure is essentially the same, except there is no reference slightly complicating matters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM