defaultmap
It can be useful to not have to worry about missing keys in a map. If a key is requested that doesn't have a value a default value is simply returned. This is exactly what this library provides.
Examples
Counter
A clear use case of this is when counting the unique elements in a list. Here you want to add one to the existing value in the map for that key. This is a problem for the first addition when there's no value for the key yet. With this library you can specify when creating the map that the default value should be zero.
# use *;
let nums = ;
let mut counts: = new;
// DefaultHashMap::default() is equivalent.
for num in nums.into_iter
println!;
// DefaultHashMap { map: {1: 1, 3: 2, 2: 1, 4: 3}, default: 0 }
# assert_eq!;
# assert_eq!;
# assert_eq!;
# assert_eq!;
Synonym lists
Another way the default map can be used is using a map filled with other collections, such as a
a Vec
, a HashMap
or even another default map.
Next follows some code to create a map where we start with tuples of synonyms and we end with a
map that contains the list of synonyms for each word.
# use *;
let synonym_tuples = ;
let mut synonym_map: = new;
// DefaultHashMap::default() is equivalent.
for & in synonym_tuples.into_iter
assert_eq!;
assert_eq!;
assert_eq!;