TypedMap
TypedMap
is a typed HashMap
. It allows you to define different value type depending on a Key type. It's useful if you want to store different key-value pairs in a single hashmap, for example in HTTP app that implements multiple services.
use ;
// Define key types
;
;
;
;
// Define value type for key types
// Create a new empty map
let mut animal_sounds: TypedMap = new;
// Insert data
animal_sounds.insert;
animal_sounds.insert;
// Get for Dog key get value of type Bark.
let spiky_volume = animal_sounds.get.unwrap.volume;
assert_eq!;
// Define key types
;
;
// Define value type for key types
// Create a new empty map
let mut data: TypedMap = new;
// Insert data
data.insert;
data.insert;
You can use special Marker
type to create more "type" key-value bindings.
;
;
use ;
;
;
;
;
let mut configs: = new;
let mut services: = new;
configs.insert;
configs.insert;
services.insert;
services.insert;
If dashmap
feature is enabled, one can use TypedDashMap
that can be used concurrently, as it's using Dashmap
under the hood.
use Arc;
use TypedDashMap;
use TypedMapKey;
;
;
;
// Implement key-value mapping for Configs marker
// Implement key-value mapping for Services marker
;
// Implement key-value mapping for Configs marker
// Implement key-value mapping for Services marker
// Implement key-value mapping for default (i.e. ()) marker
let configs: = new;
let services: = new;
let default: = new;
let configs1 = clone;
let services1 = clone;
let t1 = spawn;
// Line below would not compile, because TypeMapKey<Marker=()>
// is not implemented for Key.
// default.insert(Key(0), 1);
// Line below would not compile, because SerivceA key defines
// type value as usize for Configs marker (not &'static str)
// configs.insert(ServiceA(0), "one");
let configs2 = clone;
let services2 = clone;
let default2 = clone;
let t2 = spawn;
t1.join.unwrap;
t2.join.unwrap;
Related:
- type-map - hashmap that uses types as keys
License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.