Skip to content

key_by

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.

use helpers4::array::key_by;

Cargo feature array (enabled by default). To compile only this module:

cargo add helpers4 --no-default-features --features array

or in Cargo.toml:

[dependencies]
helpers4 = { version = "0.0.5", default-features = false, features = ["array"] }
pub fn key_by<T: Clone, K: Eq + Hash>(items: &[T], mut key: impl FnMut(&T) -> K) -> HashMap<K, T>
ParameterTypeDescription
items&[T]The elements to index.
keyimpl FnMut(&T) -> KReturns the key to index each element under.

HashMap<K, T>

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));

src/array/key_by.rs