Macro maplit::convert_args
source · macro_rules! convert_args { (keys=$kf:expr, $macro_name:ident !($($k:expr),* $(,)*)) => { ... }; (keys=$kf:expr, values=$vf:expr, $macro_name:ident !($($k:expr),* $(,)*)) => { ... }; (keys=$kf:expr, values=$vf:expr, $macro_name:ident !( $($k:expr => $v:expr),* $(,)*)) => { ... }; (keys=$kf:expr, $macro_name:ident !($($rest:tt)*)) => { ... }; (values=$vf:expr, $macro_name:ident !($($rest:tt)*)) => { ... }; ($macro_name:ident ! $($rest:tt)*) => { ... }; }
Expand description
Macro that converts the keys or key-value pairs passed to another maplit
macro. The default conversion is to use the Into
trait, if no
custom conversion is passed.
The syntax is:
convert_args!(
keys=
function ,
values=
function ,
macro_name !(
[ key => value [, key => value … ] ] ))
Here macro_name is any other maplit macro and either or both of the
explicit keys=
and values=
parameters can be omitted.
Note To use convert_args
, the macro that is being wrapped
must itself be brought into the current scope with #[macro_use]
or use
.
§Examples
#[macro_use] extern crate maplit;
use std::collections::HashMap;
use std::collections::BTreeSet;
// a. Use the default conversion with the Into trait.
// Here this converts both the key and value string literals to `String`,
// but we need to specify the map type exactly!
let map1: HashMap<String, String> = convert_args!(hashmap!(
"a" => "b",
"c" => "d",
));
// b. Specify an explicit custom conversion for the keys. If we don't specify
// a conversion for the values, they are not converted at all.
let map2 = convert_args!(keys=String::from, hashmap!(
"a" => 1,
"c" => 2,
));
// Note: map2 is a HashMap<String, i32>, but we didn't need to specify the type
let _: HashMap<String, i32> = map2;
// c. convert_args! works with all the maplit macros -- and macros from other
// crates that have the same "signature".
// For example, btreeset and conversion from &str to Vec<u8>.
let set: BTreeSet<Vec<u8>> = convert_args!(btreeset!(
"a", "b", "c", "d", "a", "e", "f",
));
assert_eq!(set.len(), 6);