Macro Rules Build HashMap Literals

Define a declarative macro_rules! macro that expands k => v pairs into HashMap insert calls, giving collection literals without repeating boilerplate.

RustData Integrity

Code

rustsnippet
22 lines
/// macro_rules! builds a HashMap literal from k => v pairs
macro_rules! map {
    ( $( $k:expr => $v:expr ),* $(,)? ) => {{
        let mut m = ::std::collections::HashMap::new();
        $( m.insert($k, $v); )*
        m
    }};
}

fn main() {
    let ports = map! {
        "http" => 80,
        "https" => 443,
        "ssh" => 22,
    };
    println!("https = {}", ports["https"]);
    println!("{} entries", ports.len());

    // 同一宏用方括号调用也行:重复片段展开成多条 insert
    let squares = map![1 => 1, 2 => 4, 3 => 9];
    println!("3^2 = {}", squares[&3]);
}

What the file does

Macro Rules Build HashMap Literals reduces to the function main.

Watch out for

  • Nothing to set up: only standard-library calls appear.

Putting it to use

Entry signature: fn main()

Output lines are prefixed (https =, 3^2 =), which makes the outcome of each step unmistakable.

The load-bearing lines

let squares = map![1 => 1, 2 => 4, 3 => 9];
( $( $k:expr => $v:expr ),* $(,)? ) => {{
    let mut m = ::std::collections::HashMap::new();
    $( m.insert($k, $v); )*
    m
}};

Interactive Tools for This Topic

FAQ

What does Macro Rules Build HashMap Literals print when run?
The script runs standalone; its 2 labeled outputs include `https =`, `3^2 =`.