This project demonstrates various ways to import modules and functions in a Rust workspace.
The workspace is structured as follows to illustrate different import scenarios:
📂 import-example (workspace root)
│
├─ 📂 crates
│ │
│ ├─ 🗂 utils
│ │ ├─ 📂 src
│ │ │ ├─ 📄 lib.rs # lib entrypoint for the `utils` crate
│ │ │ ├─ 📄 add.rs # `add` module
│ │ │ └─ 📄 sub.rs # `sub` module
│ │ └─ 📦 Cargo.toml # `utils` crate's manifest
│ │
│ └─ 🗂 nested
│ ├─ 📂 src
│ │ ├─ 📄 lib.rs # lib entrypoint for the `nested` crate
│ │ └─ 📄 mul.rs # `mul` module
│ └─ 📦 Cargo.toml # `nested` crate's manifest
│
├─ 📂 src
│ ├─ 📄 main.rs # Binary entrypoint for the `import-example` crate
│ ├─ 📄 div.rs # `div` module, local to the binary crate
│ └─ 📂 helpers
│ ├─ 📄 mod.rs # `helpers` module definition
│ └─ 📄 pow.rs # `pow` submodule inside `helpers`
│
├─ 📦 Cargo.toml # Workspace's manifest
└─ 📄 README.md
- Workspace Crates: Importing from
utils
andnested
into the main binary. - Local Modules: Importing from
div.rs
(a sibling file) andhelpers/pow.rs
(a subdirectory module). - Path Overriding (
#[path]
): Using the#[path]
attribute to load modules from files with non-standard names or locations (e.g.,foo.rs
loaded as modulec
). - Visibility Control (
pub
, private,pub(crate)
): Demonstrating howpub
exposes an item publicly, the lack ofpub
makes it private to its crate (e.g., thesub
module is only usable withinutils
), andpub(crate)
restricts visibility to the crate level. - Re-exporting (
pub use
): Simplifying a crate's public API by re-exporting public items (add
) from submodules to the crate root, allowing for shorter import paths. - Grouped Imports (
use crate::{...}
): Cleaning upuse
statements by grouping imports from the same path. - Inline Modules: Defining a module directly inside
main.rs
without creating a separate file. - Glob Imports (
*
): Using a wildcard to import all public items from a module's prelude, demonstrating a common pattern for convenience. - Renaming Imports (
as
): Importing an item under a different name (e.g.,mul
asmultiply
). - External Crate Imports: Using a third-party library (
serde
) fromcrates.io
.
This setup demonstrates a comprehensive range of Rust's use
and mod
declarations in a practical project structure.