Skip to content

gist-rs/import-example

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Rust Workspace Import Examples

This project demonstrates various ways to import modules and functions in a Rust workspace.

Project Structure

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

Import Cases Covered

  1. Workspace Crates: Importing from utils and nested into the main binary.
  2. Local Modules: Importing from div.rs (a sibling file) and helpers/pow.rs (a subdirectory module).
  3. Path Overriding (#[path]): Using the #[path] attribute to load modules from files with non-standard names or locations (e.g., foo.rs loaded as module c).
  4. Visibility Control (pub, private, pub(crate)): Demonstrating how pub exposes an item publicly, the lack of pub makes it private to its crate (e.g., the sub module is only usable within utils), and pub(crate) restricts visibility to the crate level.
  5. 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.
  6. Grouped Imports (use crate::{...}): Cleaning up use statements by grouping imports from the same path.
  7. Inline Modules: Defining a module directly inside main.rs without creating a separate file.
  8. Glob Imports (*): Using a wildcard to import all public items from a module's prelude, demonstrating a common pattern for convenience.
  9. Renaming Imports (as): Importing an item under a different name (e.g., mul as multiply).
  10. External Crate Imports: Using a third-party library (serde) from crates.io.

This setup demonstrates a comprehensive range of Rust's use and mod declarations in a practical project structure.

About

import-example

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages