Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Rust的功能和语法可以通过称为宏的自定义定义进行扩展。它们被赋予名称,并通过一致的语法some_extension!(...)来调用。

有两种方法可以定义新宏:

  • 声明宏 以更高级的声明性方式定义新语法。
  • 过程宏 使用操作输入词法单元的函数来定义函数式宏、自定义派生和自定义属性。

宏调用

Syntax
MacroInvocation
    SimplePath ! DelimTokenTree

DelimTokenTree
      ( TokenTree* )
    | [ TokenTree* ]
    | { TokenTree* }

TokenTree
    Tokenexcept delimiters | DelimTokenTree

MacroInvocationSemi
      SimplePath ! ( TokenTree* ) ;
    | SimplePath ! [ TokenTree* ] ;
    | SimplePath ! { TokenTree* }

宏调用在编译时展开宏,并用宏的结果替换该调用。宏可以在以下情况中调用:

当用作项或语句时,使用MacroInvocationSemi形式,如果未使用大括号,则末尾需要分号。可见性限定符绝不允许出现在宏调用或macro_rules定义之前。

#![allow(unused)]
fn main() {
// 用作表达式。
let x = vec![1,2,3];

// 用作语句。
println!("Hello!");

// 用在模式中。
macro_rules! pat {
    ($i:ident) => (Some($i))
}

if let pat!(x) = Some(1) {
    assert_eq!(x, 1);
}

// 用在类型中。
macro_rules! Tuple {
    { $A:ty, $B:ty } => { ($A, $B) };
}

type N2 = Tuple!(i32, i32);

// 用作项。
use std::cell::RefCell;
thread_local!(static FOO: RefCell<u32> = RefCell::new(1));

// 用作关联项。
macro_rules! const_maker {
    ($t:ty, $v:tt) => { const CONST: $t = $v; };
}
trait T {
    const_maker!{i32, 7}
}

// 宏内的宏调用。
macro_rules! example {
    () => { println!("Macro call in a macro!") };
}
// 外部宏`example`展开后,内部宏`println`也会展开。
example!();
}

宏调用可以通过两种作用域进行解析: