Rust 宏中的 tt 元变量类型是什么意思? [英] What does the tt metavariable type mean in Rust macros?
问题描述
我正在阅读一本关于 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
主要
()
- ∅
println
!
("Hello world!")
世界你好!"
每个组成一棵树,其中简单的标记(
fn
、main
等)是叶子,而任何被()
、[]
或{}
有一个子树.请注意,(
不会单独出现在令牌树中:如果不匹配相应的)
,则无法匹配(
.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 toformat_args!
. Which means thatprintln!
does not need to know the actual format and do complicated matching with it.这篇关于Rust 宏中的 tt 元变量类型是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!