在宏中使用 Hashmap 作为 TokenTree

Use Hashmap in macro as TokenTree

我遇到了一个非常奇怪的案例,似乎很容易解决,但无论我尝试做什么,我都无法找到合适的解决方案。

我正在使用外部库,它为我提供了一个以 tt (TokenTree) 作为参数的宏。用法语法如下所示:

some_macro!(
    "some name"  => "some value",
    "other name" => "other value"
); 

我的解决方案逻辑为我提供了 Hashmap 个键和值,我想将其映射到该 TokenTree。可能吗?

some_macro!(my_hashmap);

当然我在编译时并不知道所有的键

有一个问题:我必须使用稳定版本的 Rust。

我不熟悉这个库,但是,你想要的似乎是可能的。查看文档,您似乎可以使用拥有的字符串和键值对切片而不是字符串文字。如果您正在使用 HashMap 并将内容加载到宏中,它可能看起来像这样:

fn hash_map_to_counter(map:HashMap<String,String>){
  let labels:Vec<_> = map.drain().collect();
  counter!("some name", 12, &labels);
}