Modules 101 question

Explaining Rust’s Modules: Answering once and for all, “Where should we put these files?”

After reading this piece. I'm still trying to answer “Where should I put mod files?”

For the directory structure

|-- src
|-- target 
|-- .gitignore
|-- Cargo.lock
|-- Cargo.toml

? Where do I put file, so that all subsequent cargo-created files can access using the statement ' mod my_module ;' ?

Here's an example with four files:

// src/
pub mod my_module1;
pub mod my_module2;

fn main() {
// src/
use crate::my_module2::func2;

pub fn func1() {

pub fn func4() {
    println!("Hello world!");
// src/my_module2/
mod my_submodule;

pub fn func2() {
// src/my_module2/
use crate::my_module1;

pub fn func2() {

To be clear, each file should be mentioned by a mod statement exactly once, except for which should be mentioned exactly zero times. Any other accesses to the file should go through a use statement.

Many thanks,,,What you refer to as src/ is clearly under my_project/src/

? Do I place and under
my_project1 /src / and
my_project2 /src /
.. to ensure they are available to all future created cargo projects ?

To reduce directory clutter, is it possible to store all module files under a single directory " my_modules / src/ which contains,, ...etc

So you have some code that you want to re-use across multiple Cargo projects? The way to do this is to make a library:

cargo new --lib my_library

Instead of a src/, this will have a src/ as its “root” module. Any types/functions/submodules in this root module that are marked pub will be usable from within other Cargo projects. For example:

// my_library/src/
pub fn do_stuff() {

To use this code from one of your binary projects like my_project, you can put the following in my_project/Cargo.toml:

my_library = { path = "../my_library" }

(The path value can be either an absolute path or a relative path to the my_library directory.)

Now, everywhere within my_project, you can access public items from the my_library crate, just like you can from other libraries:

// my_project/src/
fn main() {

Looks like I should forget about my using modules and switch over to libraries instead.

Note that you can still use modules to organize code within each crate (whether it's a binary or library). But a library is the way to share code used by multiple crates.

For example, you could put all your common code into a single library, divided into different modules. And then all your binary projects could depend on that library.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.