map-macro

Build Status Latest Version Downloads Docs License: MIT

This crate offers declarative macros for initializing collections from the standard library.

This crate has zero dependencies.

Example

```rust use mapmacro::hashmap;

let hello = hash_map! { "en" => "Hello", "de" => "Hallo", "fr" => "Bonjour", "es" => "Hola", }; ```

Explicitly Typed Values for Trait Objects

As shown in the example above, the compiler uses type inference to infer the correct type for the created map. Unfortunately, type inference alone can not detect trait objects. This will not work, because the compiler is unable to figure out the right type:

```compile_fail use std::collections::HashMap; use std::fmt::Debug;

use mapmacro::hashmap;

let hello: HashMap<&str, &dyn Debug> = hash_map! { "en" => &"Hello", "de" => &"Hallo", "fr" => &"Bonjour", "es" => &"Hola", }; ```

The map_e! macro enables you to use trait objects as values through type coercion, making the example above compile successfully:

```rust use std::collections::HashMap; use std::fmt::Debug;

use mapmacro::hashmap_e;

let hello: HashMap<&str, &dyn Debug> = hashmape! { "en" => &"Hello", "de" => &"Hallo", "fr" => &"Bonjour", "es" => &"Hola", }; ```

Note that you need to give an explicit type to the binding when you use map_e!, because it relies on knowing what type it should coerce the values to. Also, only values and not keys can be trait objects, because keys must implement the Hash trait, which is not object safe.

Where the trait bounds on generic type parameters of the collections allow trait objects, macros for explicitly typed variants are provided. The explicitly typed versions of the macros are indicated by an _e suffix.