hbprotoss
hbprotoss

Reputation: 1395

Better way to call rust function in other file within the same directory?

I have a directory like this:

.
├── a.rs
├── b.rs
└── main.rs

main.rs:

mod a;
use a::a;

fn main() {
    println!("Hello, world!");
    a();
}

a.rs:

mod b;
use b::b;

pub fn a() {
    b();
}

b.rs:

pub fn b() {
    println!("b");
}

rustc complaints in a.rs about

file not found for module `b`

help: to create the module `b`, create file "src/a/b.rs" or "src/a/b/mod.rs"rustc(E0583)

If I put mod b; in main.rs, and replace mod b; with use crate::b::b; in a.rs, everything works well.

My question is: do I have to put every mod xxx; in the file where main() locates? I just want to call functions in the same-level rs files

Upvotes: 2

Views: 1162

Answers (1)

tobihans
tobihans

Reputation: 372

When you put mod b; in a.rs, b will be considered as a submodule of module a. So, as suggested by rustc, it should be either in "src/a/b/mod.rs" or "src/a/b.rs". And when you put it instead in main.rs, it means that this module in located at the crate root, reason why it works without any problem because rustc looks for the file in the same directory as main.rs("src") and find it.

So, you don't have to put every mod xxx where main is located. If you creating an hierarchy (I mean modules and submodules and so on), you should respect the directory architecture and put mod xxx, only in the parent module, if any. You declare mod xxx in your main file for top level modules only.

You can see more explanation in the book :).

Upvotes: 1

Related Questions