tt元变量类型在Rust宏中意味着什么? [英] What does the tt metavariable type mean in Rust macros?

查看:362
本文介绍了tt元变量类型在Rust宏中意味着什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读一本有关Rust的书,并开始使用 Rust宏.除了最后一个-tt外,所有元变量类型都在此处进行了说明并提供了示例.根据这本书,这是一棵单一令牌树".我很好奇,它是做什么用的?您能举个例子吗?

I'm reading a book about Rust, and start playing with Rust macros. All metavariable types are explained there and have examples, except the last one – tt. According to the book, it is a "a single token tree". I'm curious, what is it and what is it used for? Can you please provide an example?

推荐答案

引入此概念是为了确保宏调用中的内容正确匹配()[]{}对. tt将匹配任何单个标记括号/括号/大括号及其内容.

That's a notion introduced to ensure that whatever is in a macro invocation correctly matches (), [] and {} pairs. tt will match any single token or any pair of parenthesis/brackets/braces with their content.

例如,对于以下程序:

fn main() {
    println!("Hello world!");
}

令牌树将是:

  • fn
  • main
  • ()
    • fn
    • main
    • ()
      • println
      • !
      • ("Hello world!")
        • "Hello world!"
        • println
        • !
        • ("Hello world!")
          • "Hello world!"

          每一个都形成一棵树,简单的标记(fnmain等)是叶子,而被()[]{}包围的任何事物都有一个子树.请注意,(不会单独出现在令牌树中:如果不匹配相应的),则不可能匹配(.

          Each one forms a tree where simple tokens (fn, main etc.) are leaves, and anything surrounded by (), [] or {} has a subtree. Note that ( does not appear alone in the token tree: it's not possible to match ( without matching the corresponding ).

          例如:

          macro_rules! {
              (fn $name:ident $params:tt $body:tt) => { /* … */ }
          }
          

          将上述功能与$name → main$params → ()$body → { println!("Hello world!"); }匹配.

          would match the above function with $name → main, $params → (), $body → { println!("Hello world!"); }.

          令牌树是要求最少的元变量类型:它匹配任何内容.它通常用在根本不在乎"部分的宏中,尤其是在具有头"和尾部"部分的宏中.例如,println!宏具有与($fmt:expr, $($arg:tt)*)匹配的分支,其中$fmt是格式字符串,而$($arg:tt)*表示其余所有",并被转发到format_args!.这意味着println!不需要知道实际的格式并对其进行复杂的匹配.

          Token tree is the least demanding metavariable type: it matches anything. It's often used in macros which have a "don't really care" part, and especially in macros which have a "head" and a "tail" part. For example, the println! macros have a branch matching ($fmt:expr, $($arg:tt)*) where $fmt is the format string, and $($arg:tt)* means "all the rest" and is just forwarded to format_args!. Which means that println! does not need to know the actual format and do complicated matching with it.

          这篇关于tt元变量类型在Rust宏中意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆