版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/varding/article/details/48229949
nightly版本可以用 trace_macros!
,具体看这个:
http://stackoverflow.com/questions/30200374/how-do-i-debug-macros
下面是我写的列子:
#![feature(trace_macros)]
trace_macros!(true);
macro_rules! foo{
($x:ident,$f:ident)=>{
match $x {
3=>{
$f(100);
},
_=>{
},
};
}
}
fn bar(i:i32){
println!("hello:{:}",i);
}
fn main(){
let x = 3;
foo!(x,bar);
}
Play地址:http://is.gd/ENOHWJ
输出结果:
println! { "hello:{:}" , i }
print! { concat ! ( "hello:{:}" , "\n" ) , i }
foo! { x , bar }
hello:100
这个结果并不好,不能看到宏展开的过程
stable版本可以用这个命令:
rustc xxx.rs --pretty expanded -Z unstable-options
macro_rules! foo{
($x:ident,$f:ident)=>{
match $x {
3=>{
$f(100);
},
_=>{
},
};
}
}
fn bar(i:i32)->i32{
i + 100
}
fn main(){
let x = 3;
foo!(x,bar);
let v = vec![1,2,3];
}
输出:
#![feature(no_std)]
#![no_std]
#[prelude_import]
use std::prelude::v1::*;
#[macro_use]
extern crate std as std;
fn bar(i: i32) -> i32 { i + 100 }
fn main() {
let x = 3;
match x { 3 => { bar(100); } _ => { } };
let v = <[_]>::into_vec(::std::boxed::Box::new([1, 2, 3]));
}
用这个命令可以看到完整的展开过程,比如
foo!(x,bar);
展开成了:match x { 3 => { bar(100); } _ => { } };
这个看着就很直观了
let v = vec![1,2,3];
展开成:let v = <[_]>::into_vec(::std::boxed::Box::new([1, 2, 3]));
目前不知道怎么用cargo build 展开,所以单独新建了一个rs文件看宏展开