The macro usage scope in Rust 1.7.0 contains three scenarios:
The first case is that the macro is defined in the current file. This file may be the default module for crate, or it may be a random module.
Another scenario is that the macro is defined in the current crate. But not in the current file, but in other module modules.
The third case is that the macro is defined in other crate. or other crate sub-modules.
Use #[macro_use] To enable macros in the annotated module module to be applied to the current scope. or gaze at the macro in crate applied to the current crate scope.
Examples of the first case:
macro_rules! say_hello{ ()=>( println!("Hello"); )}fn main(){ say_hello!();}
Another situation:
- First create a new file macros.rs, define a macro Say_bonjour
macro_rules! say_bonjour{ ()=>( println!("Bonjour"); )}
#[macro_use]pubmod macros;macro_rules! say_hello{ ()=>( println!("Hello"); )}fn main(){ say_hello!(); say_bonjour!();}
The third case: staring at an external crate statement
Create a log project
cargo new log
In the log project, lib.rs is the portal, and the Macors module is defined in the lib.rs.
...#[macro_use]mod macros;...
Then, create the corresponding mod macros macros.rs file VI src/macros.rs
Declare the macro log, error, warn, info, and add #[macro_export before each macro definition) gaze. Indicates that these macros can be used by external crate.
...#[macro_export]macro_rules! Log {...}#[macro_export]macro_rules! Error {(Target: $target: Expr,$($arg: TT) = (log! (Target: $target,$crate:: Loglevel::error,$($arg)*); ); ($($arg: TT) = (log! ($crate:: Loglevel::error,$($arg)*); )}#[macro_export]macro_rules! Warn {(Target: $target: Expr,$($arg: TT) = (log! (Target: $target,$crate:: Loglevel::warn,$($arg)*); ); ($($arg: TT) = (log! ($crate:: Loglevel::warn,$($arg)*); )}#[macro_export]macro_rules! Info {(Target: $target: Expr,$($arg: TT) = (log! (Target: $target,$crate:: Loglevel::info,$($arg)*); ); ($($arg: TT) = (log! ($crate:: Loglevel::info,$($arg)*); )}...
Use: When introducing log crate, specify #[macro_use]
#[macro_use] extern crate log ; .... if !shutdown.load (ORDERING::SEQCST) {info! ( "Connectionhandler:read timed out ({:?}). Server not shutdown, so retrying read. ", err); continue ; } else {info! ( "Connectionhandler:read timed out ({:?
break ; } . . .
How to use
Rust 1.7.0 macro macro #[macro_use]