Sunday, 25 September 2016

Rust lang - initialize HashSet HashMap with constant members

Rust programming language is short of examples, how to initialize HashSet and HashMap variables with constant members. The following example demonstrates usage of seq macro rule for variables set, map1 and map2. Last th expression for the HashMap variable map3 demonstrates initialization with  constant elements without usage of macro 'seq!'.


/////////// main.rs ////////////////////
use std::collections::{HashMap,HashSet};

// from https://github.com/rust-lang/rust/issues/14726
macro_rules! seq {
    ($($x:expr),+) => {
        [$($x,)+].iter().map(|&x| x).collect()
    }
}

fn main() {
    let set: HashSet = seq!(1, 2, 3);
    let map1: HashMap = seq!((1, 10), (2, 20), (3, 30));
    let map2: HashMap<&'static str, &'static str> =
    seq!(("A", "1"),
        ("B", "2"),
        ("C", "3"));

    // demonstrate without macro
    let map3: HashMap<&'static str, &'static str> =
    [ ("A", "1"),
      ("B", "2"),
      ("C", "3") ]
      .iter().map(|&x| x).collect();
  
    println!("Set: {:?}", set);
    println!("Map: {:?}", map1);
    println!("Map: {:?}", map2);
    println!("Map: {:?}", map3);
}

No comments:

Post a Comment