Binary package: access submodules in examples

I have a binary project with several submodules and an example folder with some examples:

src
|__ mod_a/
| |__ mod.rs
|
|__ mod_b/
| |__ mod.rs
|
| __ examples/
| |__ ex1.rs
|
|__ main.rs

From the examples folder I cannot access to neither mod_a nor mod_b. I tried to use keywords like crate, extern crate to no avail.
I can guess this is only available for lib projects, is there any workararound for binary projects?

You have to properly integrate your examples folder into the module structure of your crate. I.e. add a examples/mod.rs file with:

mod ex1;

and in your main.rs file add:

mod examples;

Then you can import mod_a in examples/ex1.rs:

use crate::mod_a;

If you want examples like they are supported by Cargo, note that you need to put the examples folder at the top-level of your crate (above src/) (see here) and add a library to your package. The latter is as easy as adding a lib.rs file next to your main.rs, where you define the modules instead of in main.rs:

pub mod mod_a;
pub mod mod_b;

and change the imports in your main.rs to start with your crate name:

use your_crate::mod_a;

If you do that you can access the public items from your library in your examples/, like you'd do in main.rs (examples are compiled to binaries, just like main.rs).

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.