Table of contents
Open Table of contents
Module per file
📂 foo
├─ 📂 src
│ ├─ 📄 utils.rs # module
│ └─ 📄 main.rs
└─ 📦 Cargo.toml
utils.rs
pub fn hello() {
println!("hello world!");
}
main.rs
mod utils; // load modules
use utils;
fn main () {
utils.hello(); // call functions from module
}
Module per folder
📂 foo
├─ 📂 src
│ │
│ ├─ 📂 utils
│ │ ├─ 📄 mod.rs # module entry point
│ │ ├─ 📄 say.rs
│ │ └─ 📄 cast.rs
│ │
│ └─ 📄 main.rs
│
└─ 📦 Cargo.toml
mod.rs
pub mod say; // declare public access to function (exports)
say.rs
pub fn hello() { // 👈 make it public, or just pub(crate) for internal use.
println!("hello world!");
}
cast.rs
use super::say // load say
pub fn cast() {
say.hello(); // use function
}
main.rs
mod utils; // load module
use utils::say; // using say
fn main() {
say.hello(); // call the functions
}
Lib
Create lib using cargo init <package> --lib
cargo init bar --lib
📂 bar
├─ 📂 src
│ └─ 📄 lib.rs # lib entrypoint
└─ 📦 Cargo.toml
lib.rs
pub fn hello() {
println!("hello world!");
}
Using libs
- loading via
Cargo.toml
[dependencies]
foo = { git="https://YOU_GITHUB_REPO_URL"}
- Publish package and use
cargo add <package>
- loading via
workspace
Workspace
📂 workspace-example
│
├─ 🗂 utils
│ ├─ 📂 src
│ │ └─ 📄 lib.rs # lib entrypoint.
│ └─ 📦 Cargo.toml
│
├─ 📂 foo
│ ├─ 📂 src
│ │ └─ 📄 main.rs # app entrypoint.
│ └─ 📦 Cargo.toml
│
└─ 📦 Cargo.toml
foo/Cargo.toml
[dependencies]
foo = { path="../utils" }
Cargo.toml
[workspace]
members = [
"utils",
"foo",
]