How to refer methods in another module from module

I have a project with the following structure:



// a/

pub mod a1;

// b/

pub mod b1;

I want to use helper functions in from, how can I do it?

Module b1 lives at crate::b::b1. You can do one of the following: (crate here is the crate keyword, not the name of your crate)

crate::b::b1::function(1, 2);

// or

use crate::b::b1;

b1::function(1, 2)

Hi thanks for reply!
I also have some macros defined in b1, how can I use them in

macro should be same. I'm using vscode and it gives me hint that can't find the macro but actually the file can compile.

ah, it can't compile. The macro I used is in test, when I run cargo build it won't be built, so I still can't use the macros.

macro_rules! macros within the same crate are scoped slightly oddly - you'll first need to use #[macro_use] on the module in the parent scope to bring them "up", and then they'll be usable in any module defined after that statement.

So, in b/, you'd want to add #[macro_use] to

mod b1;

And then in, you'd add #[macro_use] to a to re-export them to the top level. Additionally, you'll want to make sure that b is declared after a. Locally defined macros are picked up and become usable in the same order they're defined, which helps with making code well-defined, but can be annoying to use if macros are defined and used throughout the crate.

mod b;

// after `mod b`:
mod a;

There's a chapter in the book on this import mechanic, not that it goes into too much more detail:

My general strategy for dealing with order-dependence is to have all macros either completely local - used only directly after they're defined - or put into a module that is "above" all other modules and that the whole crate shares.

1 Like

Thanks! It works.

1 Like