Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting declarative macro that uses functions defined in crate

I'm trying to export a macro that uses from some functions defined in the crate. Something like this for e.g in a crate named a_macro_a_day

// lib.rs

pub fn a() {}

#[macro_export]
macro_rules! impl_helper_funcs {
  use crate::a; // error unresolved import
  use a_macro_a_day::a; // error unresolved import
  fn b() {
    ...
    a() // call imported a here
  }
}

I've tried using various combinations of use to import a but the error always shows up the macro definition saying unresolved import crate or unresolved import a_macro_a_day.

I would prefer not to go with the procedural macro way as this is simply trying to reduce code duplication. Is there any way to export a macro that imports local (but public) functions?

like image 382
twitu Avatar asked Oct 16 '25 00:10

twitu


1 Answers

In declarative macros, you should use $crate to access items in the current crate. And your macro declaration is missing a match and a body.

Try this:

// lib.rs

pub fn a() {}

#[macro_export]
macro_rules! impl_helper_funcs {
 // vvvvvvv add this
    () => {
        use $crate::a;
        //  ^ add this
        fn b() {
            // ...
            a() // call imported a here
        }
    };
 // ^^ add this
}
like image 161
Sprite Avatar answered Oct 18 '25 14:10

Sprite



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!