[英]Using another macro in a macro_rules without requiring `extern crate` in rust
Is there a way to "re-export" #[macro_use] extern crate
similar to pub use
so that users of a macro using macros do not have to manually add these dependent extern crate
s? 有没有办法“重新导出”类似于pub use
#[macro_use] extern crate
,以便使用宏的宏的用户不必手动添加这些依赖的extern crate
s?
The rest of the question is an example to illustrate. 问题的其余部分是一个例子来说明。
In src/lib.rs
, note that the id
macro is using the lazy_static
macro: 在src/lib.rs
,请注意id
宏正在使用lazy_static
宏:
#[macro_export]
macro_rules! id {
() => {
lazy_static! {
static ref NUMBER : std::sync::atomic::AtomicUsize =
std::sync::atomic::AtomicUsize::new(0);
}
return NUMBER.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
}
}
In examples/example.rs
, we need an extern crate
line for each macro, even though we're just using the id
macro directly: 在examples/example.rs
,我们需要为每个宏提供一个extern crate
行,即使我们只是直接使用id
宏:
#[macro_use]
extern crate id_macro;
#[macro_use]
extern crate lazy_static;
fn new_id() -> usize {
id!();
}
fn main() {
println!("id {}", new_id()); // prints "id 0"
println!("id {}", new_id()); // prints "id 1"
}
In the example, it would be great if the user of id_macro
could use id!
在示例中,如果id_macro
的用户可以使用id!
, id_macro
id!
without knowing about lazy_static
. 不知道lazy_static
。 Is there a way to "re-export" extern crate
similar to pub use
to make the following lines go away from the example? 有没有办法“重新导出”类似于pub use
extern crate
以使以下行离开示例?
#[macro_use]
extern crate lazy_static;
There is an unstable macro_reexport
attribute. 有一个不稳定的macro_reexport
属性。
However, Rust is working on making macros ( 2.0 ) behave like normal items that support pub use
, so this attribute won't be stable and will become obsolete. 但是,Rust正致力于使宏( 2.0 )的行为与支持pub use
普通项一样,因此该属性将不稳定并且将过时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.