How to refer methods in another module from module

I have a project with the following structure:

Snipaste_2019-07-31_22-08-45

where

// a/mod.rs

pub mod a1;

// b/mod.rs

pub mod b1;

I want to use helper functions in b1.rs from a1.rs, 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 a1.rs?

UPDATED:
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.

UPDATED2:
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/mod.rs, you'd want to add #[macro_use] to b1.rs:

#[macro_use]
mod b1;

And then in lib.rs, 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.

#[macro_use]
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: https://doc.rust-lang.org/1.7.0/book/macros.html#scoping-and-macro-importexport

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 macros.rs module that is "above" all other modules and that the whole crate shares.

1 Like

Thanks! It works.

1 Like