Poperton
Poperton

Reputation: 2147

Why only main.rs can declare mod?

main.rs
main2.rs
file1.rs
src/something.rs
Cargo.toml

on main.rs, doing mod file1 works, but doing mod file1 on main2.rs leads to

file not found for module `file1`

Why only main.rs can declare sibling files with mod?

Upvotes: 4

Views: 1121

Answers (1)

Svetlin Zarev
Svetlin Zarev

Reputation: 15683

New modules can be declared from both main.rs and lib.rs. The first is used for binary crates, the latter - for libraries. It's important to note that if a package has both files, then it will have two crates with the same name (one library and one binary). You can also have multiple binary crates, if you define the crate roots (explained below) in src/bin - each file will be treated as a separate binary crate. This is explained in detail in the rust book.

These two files are special - they are called crate roots, because they form a tree-like structure. Each module should be part of it. You cannot define a module outside that tree. This is again explained in the book.

Thus in order to be able to define a new module from within main2.rs, it either has to be a crate root - i.e. it has to have a main() and be located in /src/bin/main2.rs or it has to be part of the module-tree, descending from some of the crate roots.

Upvotes: 7

Related Questions