hmap

Macro hmap 

Source
macro_rules! hmap {
    (
    $( $key : expr => $value : expr ),* $( , )?
  ) => { ... };
}
Expand description

Creates a HashMap from a list of key-value pairs.

The hmap macro allows for convenient creation of a HashMap with initial elements.

§Origin

This collection can be reexported from different crates:

  • from std, if use_std is on ( no_std flag if off )
  • from hashbrown, if use_alloc flag if on

§Syntax

The macro can be called with a comma-separated list of key-value pairs. A trailing comma is optional.

// HashMap of &str to i32
let map1 = hmap!( "one" => 1, "two" => 2, "three" => 3 );

// HashMap of &str to &str
let map2 = hmap!{ "name" => "value", "type" => "example" };

// With trailing comma
let map3 = hmap!( 1 => "one", 2 => "two", 3 => "three", );

§Parameters

  • $( $key:expr => $value:expr ),* $( , )?: A comma-separated list of key-value pairs to insert into the HashMap. Each key and value can be of any type that implements the Into<K> and Into<V> traits, where K and V are the types stored in the HashMap as keys and values, respectively.

§Returns

Returns a HashMap containing all the specified key-value pairs. The capacity of the map is automatically determined based on the number of elements provided.

§Example

Basic usage with string slices and integer values:

let map : HashMap< &str, i32 > = hmap!( "one" => 1, "two" => 2, "three" => 3 );
assert_eq!( map.get( "one" ), Some( &1 ) );
assert_eq!( map.get( "two" ), Some( &2 ) );
assert_eq!( map.get( "three" ), Some( &3 ) );

§Example

Creating a HashMap of integers to strings from literals:

let pairs = hmap!( 1 => "apple", 2 => "banana" );
assert_eq!( pairs.get( &1 ), Some( &"apple" ) );
assert_eq!( pairs.get( &2 ), Some( &"banana" ) );