Rust 如何使宏在任何地方导入/使用struct';用过什么?
假设模块中有以下代码:Rust 如何使宏在任何地方导入/使用struct';用过什么?,rust,Rust,假设模块中有以下代码: struct A{ } #[macro_export] macro_rules! profile { ($variable_name:tt, $expression:expr) => { let a = A{}; } } 因此它将位于a/a.rs中,位于a/mod.rs的一侧,该侧导出a::a,并导出宏 问题是,当我在其他模块(如b/b.rs)上使用此宏时,在使用宏之前,我必须使用super::a::a 我可以改变让a=
struct A{
}
#[macro_export]
macro_rules! profile {
($variable_name:tt, $expression:expr) => {
let a = A{};
}
}
因此它将位于a/a.rs
中,位于a/mod.rs
的一侧,该侧导出a::a
,并导出宏
问题是,当我在其他模块(如b/b.rs
)上使用此宏时,在使用宏之前,我必须使用super::a::a
我可以改变让a=a{}将宏上的code>设置为让a=self::a::a{}代码>。但是,它不能在所有模块上工作,当然也不能用于在代码中使用此库的库用户
如何指定a=something::something::a{}
在我的库中的任何地方都可以使用,也适用于此库的用户?在声明性宏中,您可以使用$crate
元变量引用定义宏的板条箱,然后使用项的绝对路径。这将在您的库内外都起作用。例如,如果您的结构A
在库中的路径module\u A::module\u b::A
处定义,您将使用:
struct A{
}
#[macro_export]
macro_rules! profile {
($variable_name:tt, $expression:expr) => {
let a = $crate::module_a::module_b::A{};
}
}