Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this rust HashMap macro no longer work?

Tags:

rust

I previously used:

#[macro_export]
macro_rules! map(
  { T:ident, $($key:expr => $value:expr),+ } => {
    {
      let mut m = $T::new();
      $(
        m.insert($key, $value);
      )+
      m
    }
 };
)

To create objects, like this:

let mut hm = map! {HashMap, "a string" => 21, "another string" => 33};

However, this no longer seems to work. The compiler reports:

- Failed:
macros.rs:136:24: 136:31 error: no rules expected the token `HashMap`
macros.rs:136     let mut hm = map! {HashMap, "a string" => 21, "another string" => 33};
                                     ^~~~~~~

What's changed with macro definitions that makes this no longer work?

The basic example below works fine:

macro_rules! foo(
  {$T:ident} => { $T; };
)

struct Blah;

#[test]
fn test_map_create() {
  let mut bar = foo!{Blah};
}

So this seem to be some change to how the {T:ident, $(...), +} expansion is processed?

What's going on here?

like image 304
Doug Avatar asked Feb 13 '23 17:02

Doug


1 Answers

You’re lacking the $ symbol before T.

like image 142
Chris Morgan Avatar answered Feb 19 '23 15:02

Chris Morgan