How to use multiple files in rust?

Viewed 4464

How to use multiple files in rust?
My main code is in file1.rs. file2.rs runs the main function of file1.rs multiple times, that's why I want to split it into 2 files, to keep my code clean. Than I just want to run the main function of file2.rs in my main.rs file. (I'm using the latest version of rust - 2021)

Folder structure:

├── Cargo.lock  
├── Cargo.toml  
├── src  
│  ├── main.rs  
│  └── file1.rs
|  └── file2.rs
└── target  

main.rs

pub mod file1;
pub mod file2;

pub fn main() {
    file2::main();
}

file2.rs

pub mod file1;

pub fn main() {
    file1::func("Bob");
    file1::func("Alice");
}

file1.rs

pub fn func(name: &str) {
    println!("Hello {}", name.to_string());
}

I get this error message:

file not found for module `file1`
to create the module `file1`, create file "src/file2/file1.rs"
or "src/file2/file1/mod.rs" rustcE0583
3 Answers

Here you are saying that file2.rs has a module called file1, so your tree should be:

src
 |
  ---- main.rs
  ---- file2.rs
  ---- file2
        |
        ----- file1.rs

Or change it to:

main.rs:

pub mod file1;
pub mod file2;

// ...

file2.rs:

// pub mod file1

// ...

You need to make the main functions public using pub fn main() {...}. Also, the syntax you used to call the file1::main is invalid, you would have to provide actual values like 1 and "foo".

You can import from other modules (files) in the same directory:

use super::file2::*;
Related