宏
Rust 的功能和语法可以通过名为宏的自定义定义来扩展。它们被赋予名称,并通过一致的语法调用:some_extension!(...)
。
有两种方法来定义新的宏
宏调用
语法
宏调用 :
简单路径!
定界符标记树定界符标记树 :
(
标记树*)
|[
标记树*]
|{
标记树*}
宏调用分号 :
简单路径!
(
标记树*)
;
| 简单路径!
[
标记树*]
;
| 简单路径!
{
标记树*}
宏调用在编译时展开宏,并将调用替换为宏的结果。宏可以在以下情况下调用
当用作项或语句时,如果未使用花括号,则使用 宏调用分号 形式,其中需要在末尾使用分号。可见性限定符 绝不允许出现在宏调用或 macro_rules
定义之前。
#![allow(unused)] fn main() { // Used as an expression. let x = vec![1,2,3]; // Used as a statement. println!("Hello!"); // Used in a pattern. macro_rules! pat { ($i:ident) => (Some($i)) } if let pat!(x) = Some(1) { assert_eq!(x, 1); } // Used in a type. macro_rules! Tuple { { $A:ty, $B:ty } => { ($A, $B) }; } type N2 = Tuple!(i32, i32); // Used as an item. use std::cell::RefCell; thread_local!(static FOO: RefCell<u32> = RefCell::new(1)); // Used as an associated item. macro_rules! const_maker { ($t:ty, $v:tt) => { const CONST: $t = $v; }; } trait T { const_maker!{i32, 7} } // Macro calls within macros. macro_rules! example { () => { println!("Macro call in a macro!") }; } // Outer macro `example` is expanded, then inner macro `println` is expanded. example!(); }