? Where do I put file my_module.rs, so that all subsequent cargo-created files main.rs can access my_module.rs using the statement ' mod my_module ;' ?
// src/my_module2/mod.rs
mod my_submodule;
pub fn func2() {
my_submodule::func3();
}
// src/my_module2/my_submodule.rs
use crate::my_module1;
pub fn func2() {
my_module1::func4();
}
To be clear, each file should be mentioned by a mod statement exactly once, except for main.rs 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/main.rs is clearly under my_project/src/main.rs
? Do I place my_module1.rs and my_module2.rs under
my_project1 /src /my_module1.rs and
my_project2 /src /my_module2.rs
.. 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
my_mod1.rs, my_mod2.rs, ...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/main.rs, this will have a src/lib.rs 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:
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.