How to include files from same directory in a module using Cargo/Rust?

Neo picture Neo · Oct 19, 2017 · Viewed 12.2k times · Source

I have a Cargo project consisting of three files in the same directory: main.rs, mod1.rs and mod2.rs.

I want to import functions from mod2.rs to mod1.rs the same way I would import functions from mod1.rs to main.rs.
I've read about the file structure required but I don't get it - naming all the imported files mod will lead to minor confusion in the editor and also this just complicates the project hierarchy.

Is there a way to import/include files independently of directory structure as I would in Python or C++?

main.rs:

mod mod1; // Works

fn main() {
    println!("Hello, world!");
    mod1::mod1fn();
}

mod1.rs:

mod mod2; // Fails

pub fn mod1fn() {
    println!("1");
    mod2::mod2fn();
}

mod2.rs:

pub fn mod2fn() {
    println!("2");
}

Building results in:

error: cannot declare a new module at this location
 --> src\mod1.rs:1:5
  |
1 | mod mod2;
  |     ^^^^
  |
note: maybe move this module `src` to its own directory via `src/mod.rs`
 --> src\mod1.rs:1:5
  |
1 | mod mod2;
  |     ^^^^
note: ... or maybe `use` the module `mod2` instead of possibly redeclaring it
 --> src\mod1.rs:1:5
  |
1 | mod mod2;
  |     ^^^^

I can't use it as it doesn't exist as a module anywhere, and I don't want to modify the directory structure.

Answer

Joe Clay picture Joe Clay · Oct 19, 2017

All of your top level module declarations should go in main.rs, like so:

mod mod1;
mod mod2;

fn main() {
    println!("Hello, world!");
    mod1::mod1fn();
}

You can then use crate::mod2 inside mod1:

use crate::mod2;

pub fn mod1fn() {
    println!("1");
    mod2::mod2fn();
}

I'd recommend reading the chapter on modules in the new version of the Rust book if you haven't already - they can be a little confusing for people who are new to the language.