1

Apologies, if it's a duplicate questions. I looked online / stackoverflow and I couldn't find the answer. I want to import modules from different folders / files in Rust.

The structure of my files/ folders is the following:

src/
  test_1/
     mod.rs <- inside here I have put: pub mod a, and pub mod b
     a.rs
     b.rs
  tes_2/ 
     mod.rs <- inside here I have put: pub mod a1, and pub mod b1
     a1.rs
     b1.rs
  test_3/
     mod.rs<- inside here I have put: pub mod a2, and pub mod b2
     a2.rs
     b2.rs

I want to share code I have in a.rs with a1.rs and a2.rs or the code I have in b2.rs with a.rs.

I have tried to add mod and use inside the files, I have also try many examples online but nothing worked.

Can you please help? Thanks in advance.

user3698971
  • 297
  • 1
  • 3
  • 12
  • 1
    Hi there! Are you using Cargo? Do you have a `src/lib.rs` or `src/main.rs`? Have you seen [this](https://stackoverflow.com/q/26388861/2408867) or [this](https://stackoverflow.com/q/45519176/2408867) Q&A? Do they help? – Lukas Kalbertodt Nov 01 '19 at 18:54
  • 1
    @LukasKalbertodt you comment helped a lot, please see my answer. Thanks – user3698971 Nov 01 '19 at 19:03

1 Answers1

3

After looking online, and after Lukas comment, I found the solution. I will try to summarise it here.

I had to create a new file named lib.rs outside of the folders:

src/
  test_1/
     mod.rs <- inside here I have put: pub mod a, and pub mod b
     a.rs
     b.rs
  test_2/ 
     mod.rs <- inside here I have put: pub mod a1, and pub mod b1
     a1.rs
     b1.rs
  test_3/
     mod.rs<- inside here I have put: pub mod a2, and pub mod b2
     a2.rs
     b2.rs
  lib.rs 

Inside this file, I added the following code:

pub mod test_1
pub mod test_2
pub mod test_3

And it worked! I can now import code from different files using the use crate command:

Example: use create::test_1::a1::function_name;

Westy92
  • 19,087
  • 4
  • 72
  • 54
user3698971
  • 297
  • 1
  • 3
  • 12