As our crate grows and has more and more structs, enums, and functions, putting everything in the src/main.rs file will start to be confusing.
In order to better organize our code we might want to split it into multiple files. (and later maybe into multiple crates, but for now let's keep them in the same crate.
The functions
-
It has one function called
in_mainand we can call it without any extra effort. -
In the
src/lib.rsfile we have function calledin_lib.-
It is declared with the
pubkeyword to make it public. -
We can call it by prefixing the name with the name of the crate
app::in_lib();. (appis the name of the crate as defined in theCargo.tomlfile.)
-
-
In the
src/helper.rsfile there is a function calledin_helper. In order to make it usable in the main file:- We made it public with the
pubprefix. - We also added
pub mod helper;to thesrc/lib.rsfile. - Now we can call it with its full name:
app::helper::in_helper();
- We made it public with the
-
Another function in the
src/helper.rscalled in_imported_helper.- We made it public with
pub. - In
src/lib.rswe addedpub use helper::in_imported_helper;(imported it) - We can now call it
app::in_imported_helper();(without the exact location of the function.)
- We made it public with
-
In order to allow a a function in
src/helper.rsto call a function insrc/lib.rs-
The function must be
pub. -
We prefix it with
crateas incrate::in_lib().
-
Cargo.toml
examples/split-code/Cargo.toml
[package]
name = "app"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
The main.rs
examples/split-code/src/main.rs
use app::tools::in_tools;
fn main() {
println!("in main function");
in_main();
app::in_lib();
app::helper::in_helper();
app::in_imported_helper();
in_tools();
}
fn in_main() {
println!("in src/main.rs");
}
lib.rs
examples/split-code/src/lib.rs
pub mod helper;
pub mod tools;
pub use helper::in_imported_helper;
pub fn in_lib() {
println!("in_lib");
helper::in_helper();
}
helper.rs
examples/split-code/src/helper.rs
pub fn in_helper() {
println!("in_helper");
}
pub fn in_imported_helper() {
println!("in_imported_helper");
crate::in_lib()
}
tools.rs
examples/split-code/src/tools.rs
pub fn in_tools() {
println!("in_tools");
crate::helper::in_helper();
}