letmutnum=5;letr1=&numas*consti32;letr2=&mutnumas*muti32;// 不安全块解引用
unsafe{println!("r1 is: {}",*r1);println!("r2 is: {}",*r2);}// 方法的定义和调用
unsafefndangerous(){}unsafe{dangerous();}
traitPilot{fnfly(&self);}traitWizard{fnfly(&self);}structHuman;implPilotforHuman{fnfly(&self){println!("This is your captain speaking.");}}implWizardforHuman{fnfly(&self){println!("Up!");}}implHuman{fnfly(&self){println!("*waving arms furiously*");}}fnmain(){letperson=Human;// 限定调用的方法
Pilot::fly(&person);Wizard::fly(&person);person.fly();}
useproc_macro::TokenStream;usequote::quote;usesyn;// 解析语法树,获取类型名称,并打印
#[proc_macro_derive(HelloMacro)]pubfnhello_macro_derive(input: TokenStream)-> TokenStream{// Construct a representation of Rust code as a syntax tree
// that we can manipulate
letast=syn::parse(input).unwrap();impl_hello_macro(&ast)}fnimpl_hello_macro(ast: &syn::DeriveInput)-> TokenStream{letname=&ast.ident;letgen=quote!{implHelloMacrofor#name{fnhello_macro(){println!("Hello, Macro! My name is {}!",stringify!(#name));}}};gen.into()}// 使用方
usehello_macro::HelloMacro;usehello_macro_derive::HelloMacro;// 引入过程宏
#[derive(HelloMacro)]structPancakes;fnmain(){// 直接调用
Pancakes::hello_macro();}