片段說明符種類的模式
在 $e:expr 中,expr 被稱為片段說明符。它告訴解析器引數 $e 期望的是什麼型別的標記。Rust 提供了各種片段說明符,允許輸入非常靈活。
| 符 | 描述 | 例子 |
|---|---|---|
ident |
識別碼 | x,foo |
path |
合格的名稱 | std::collection::HashSet,Vec::new |
ty |
型別 | i32,&T,Vec<(char, String)> |
expr |
表達 | 2+2,f(42),if true { 1 } else { 2 } |
pat |
圖案 | _,c @ 'a' ... 'z',(true, &x),Badger { age, .. } |
stmt |
宣告 | let x = 3,return 42 |
block |
大括號區塊 | { foo(); bar(); },{ x(); y(); z() } |
item |
專案 | fn foo() {},struct Bar;,use std::io; |
meta |
屬性內部 | cfg!(windows),doc="comment" |
tt |
令牌樹 | +,foo,5,[?!(???)] |
請注意,文件註釋/// comment 被視為與 #[doc="comment"] 相同的巨集。
macro_rules! declare_const_option_type {
(
$(#[$attr:meta])*
const $name:ident: $ty:ty as optional;
) => {
$(#[$attr])*
const $name: Option<$ty> = None;
}
}
declare_const_option_type! {
/// some doc comment
const OPT_INT: i32 as optional;
}
// The above will be expanded to:
#[doc="some doc comment"]
const OPT_INT: Option<i32> = None;
按照設定
某些片段說明符需要在其後面的令牌必須是受限集之一,稱為跟隨集。這為 Rust 的語法提供了一些靈活性,可以在不破壞現有巨集的情況下進行演變。
| 符 | 按照設定 |
|---|---|
expr,stmt |
=> , ; |
ty,path |
=> , = | ; : > [ { as where |
pat |
=> , = | if in |
ident,block,item,meta,tt |
任何令牌 |
macro_rules! invalid_macro {
($e:expr + $f:expr) => { $e + $f };
// ^
// `+` is not in the follow set of `expr`,
// and thus the compiler will not accept this macro definition.
($($e:expr)/+) => { $($e)/+ };
// ^
// The separator `/` is not in the follow set of `expr`
// and thus the compiler will not accept this macro definition.
}