Skip to main content

key_by

Function key_by 

Source
pub fn key_by<T: Clone, K: Eq + Hash>(
    items: &[T],
    key: impl FnMut(&T) -> K,
) -> HashMap<K, T>
Expand description

Indexes the elements of items by the key returned by key.

When several elements share a key, the last one wins. Use group_by to keep them all.

§Arguments

  • items - The elements to index.
  • key - Returns the key to index each element under.

§Examples

use helpers4::array::key_by;

let users = [("ann", 1), ("bob", 2), ("cat", 1)];
let by_id = key_by(&users, |&(_, id)| id);
assert_eq!(by_id[&2], ("bob", 2));
assert_eq!(by_id[&1], ("cat", 1));