|
1 | 1 | #![doc = include_str!("../README.md")]
|
| 2 | +//! |
| 3 | +//! ## Explicitly Typed Values for Trait Objects |
| 4 | +//! |
| 5 | +//! As shown in the example above, the compiler uses type inference to infer the correct type |
| 6 | +//! for the created map. |
| 7 | +//! Unfortunately, type inference alone can not detect [trait objects][trait objects]. |
| 8 | +//! This will not work, because the compiler is unable to figure out the right type: |
| 9 | +//! |
| 10 | +//! ```compile_fail |
| 11 | +//! use std::collections::HashMap; |
| 12 | +//! use std::fmt::Debug; |
| 13 | +//! |
| 14 | +//! use map_macro::hash_map; |
| 15 | +//! |
| 16 | +//! let hello: HashMap<&str, &dyn Debug> = hash_map! { |
| 17 | +//! "en" => &"Hello", |
| 18 | +//! "de" => &"Hallo", |
| 19 | +//! "fr" => &"Bonjour", |
| 20 | +//! "es" => &"Hola", |
| 21 | +//! }; |
| 22 | +//! ``` |
| 23 | +//! |
| 24 | +//! The `map_e!` macro enables you to use trait objects as values through |
| 25 | +//! [type coercion][type coercion], making the example above compile successfully: |
| 26 | +//! |
| 27 | +//! ```rust |
| 28 | +//! use std::collections::HashMap; |
| 29 | +//! use std::fmt::Debug; |
| 30 | +//! |
| 31 | +//! use map_macro::hash_map_e; |
| 32 | +//! |
| 33 | +//! let hello: HashMap<&str, &dyn Debug> = hash_map_e! { |
| 34 | +//! "en" => &"Hello", |
| 35 | +//! "de" => &"Hallo", |
| 36 | +//! "fr" => &"Bonjour", |
| 37 | +//! "es" => &"Hola", |
| 38 | +//! }; |
| 39 | +//! ``` |
| 40 | +//! |
| 41 | +//! Note that you need to give an explicit type to the binding when you use `map_e!`, because |
| 42 | +//! it relies on knowing what type it should coerce the values to. |
| 43 | +//! Also, only values and not keys can be trait objects, because keys must |
| 44 | +//! implement the [`Hash`][hash] trait, which is not |
| 45 | +//! [object safe][object safe]. |
| 46 | +//! |
| 47 | +//! Where the trait bounds on generic type parameters of the collections allow trait objects, |
| 48 | +//! macros for explicitly typed variants are provided. |
| 49 | +//! The explicitly typed versions of the macros are indicated by an `_e` suffix. |
| 50 | +//! |
| 51 | +//! [trait objects]: https://doc.rust-lang.org/reference/types/trait-object.html |
| 52 | +//! [type coercion]: https://doc.rust-lang.org/reference/type-coercions.html |
| 53 | +//! [object safe]: https://doc.rust-lang.org/reference/items/traits.html#object-safety |
| 54 | +//! [hash]: https://doc.rust-lang.org/std/hash/trait.Hash.html |
| 55 | +//! |
| 56 | +
|
2 | 57 | #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
|
3 | 58 | #![no_std]
|
4 | 59 |
|
|
0 commit comments