rust - 为什么这个 rust HashMap 宏不再起作用了?

标签 rust

我以前用过:

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

创建对象,像这样:

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

然而,这似乎不再有效。编译器报告:

- 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};
                                     ^~~~~~~

宏定义有什么变化使它不再有效?

下面的基本示例工作正常:

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

struct Blah;

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

所以这似乎是对 {T:ident, $(...), +} 扩展处理方式的一些改变?

这是怎么回事?

最佳答案

您在 T 之前缺少 $ 符号。

关于rust - 为什么这个 rust HashMap 宏不再起作用了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24276617/

相关文章:

rust - 如何在rust中传入flags参数?

rust - 使用 plotlib 创建 SVG 失败并显示 "invalid y_range"

reference - `&str` 可以包含指向 Rust 中程序内存的指针吗?

rust - 无法在用户定义类型的 `Vec` 内添加分配

rust - 如何将 SOL 从创建 token 关联帐户的 PDA 转移到 Anchor 中的普通帐户?

rust - get_value 返回 `f64` 而不是 `[u8; 4]`

generics - 在不固定 `Fn` 参数之一的情况下,在结构定义上指定 `Fn` trait bound

rust - 为什么要尝试!()和?在不返回Option或Result的函数中使用时无法编译?

unit-testing - 为什么我不能运行 main() 中定义的#[test]?

rust - "borrowed value does not live long enough"好像怪错了