Rust Tutorial
Estimated reading: 4 minutes 110 views

🦀 Rust – Modules, Packages & Collections: Organize, Share & Reuse Code

🧲 Introduction – Why Learn Modules, Packages & Collections in Rust?

Rust projects scale best when organized clearly. With modules, packages, and collections, Rust gives you powerful tools to structure your code, reuse functionality, and use standard containers safely and efficiently. These concepts are essential for maintainable, scalable Rust applications.

🎯 In this guide, you’ll learn:

  • How to create and use Rust modules and packages
  • How Cargo handles package management
  • Overview of Rust’s standard collections (Vec, HashMap, etc.)
  • Code examples with output and usage

📦 Rust Modules – Organize Code into Logical Units

🔹 What is a Module?

A module is a namespace for functions, structs, and enums. It helps separate functionality and control visibility.

🔹 Basic Module Example

mod greetings {
    pub fn hello() {
        println!("Hello from module!");
    }
}

fn main() {
    greetings::hello();
}

🧠 Explanation:

  • mod greetings defines a module
  • pub fn makes the function public
  • greetings::hello() calls the function

📤 Output:

Hello from module!

🗂️ File-based Modules

Split modules into multiple files:

src/
├── main.rs
└── utils.rs

main.rs

mod utils;

fn main() {
    utils::say_hi();
}

utils.rs

pub fn say_hi() {
    println!("Hi from utils!");
}

📦 Packages and Crates – Shareable Units of Rust Code

🔹 Definitions

TermMeaning
PackageA Cargo-managed project with Cargo.toml
CrateA binary or library compiled unit (1 package = ≥1 crate)
ModuleInternal structure of a crate

🔹 Cargo Project Structure

my_project/
├── Cargo.toml     # package metadata
└── src/
    └── main.rs    # root crate file

🔹 Cargo Command Usage

cargo new my_app         # Create a new binary project
cargo build              # Compile the crate
cargo run                # Build and run main.rs
cargo doc --open         # Open API docs for the crate

📚 Collections in Rust – Standard Containers

Rust provides a powerful set of standard collections in std::collections. Most are stored on the heap, grow dynamically, and follow ownership rules.

🔹 Common Collections

CollectionDescriptionUse Case
Vec<T>Growable listDynamic arrays
HashMap<K, V>Key-value storeIndex by key
HashSet<T>Unique unordered setDeduplication, membership check
VecDeque<T>Double-ended queueQueue/Deque structures
BinaryHeap<T>Priority queue (max-heap by default)Task scheduling, min/max ops
BTreeMap<K, V>Sorted key-value storeOrder-sensitive maps

📦 Using Vec, HashMap, and HashSet – Quick Examples

🔹 Vector Example:

fn main() {
    let mut v = vec![1, 2];
    v.push(3);
    println!("{:?}", v);
}

📤 Output:

[1, 2, 3]

🔹 HashMap Example:

use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();
    map.insert("apple", 3);
    println!("{:?}", map);
}

📤 Output:

{"apple": 3}

🔹 HashSet Example:

use std::collections::HashSet;

fn main() {
    let mut set = HashSet::new();
    set.insert("Rust");
    set.insert("Rust");
    println!("{:?}", set);
}

📤 Output:

{"Rust"}

🚧 Visibility and pub Keyword

KeywordMeaning
pubPublic: accessible from other modules
pub(crate)Visible within the same crate
modDefines a new module (file or inline)
useBrings names into scope for easier access

📌 Summary – Recap & Next Steps

Rust gives you modular programming power through its module system, packaging tools, and robust standard collections. Mastering these helps you structure and scale your applications with ease.

🔍 Key Takeaways:

  • Use mod, pub, and use to create reusable modules
  • Packages and crates are managed via Cargo
  • Collections like Vec, HashMap, HashSet simplify data handling
  • Cargo commands streamline project workflows

⚙️ Up next: Learn Rust – Error Handling to manage safe execution paths.


❓FAQs


What’s the difference between a crate and a module in Rust?
✅ A crate is the root compilation unit, while modules are internal subdivisions of code.


Can I define a module in a separate file?
✅ Yes! Create mod_name.rs or a folder mod_name/mod.rs and declare mod mod_name; in your root file.


When should I use Vec vs Array?
✅ Use Vec for dynamic size, Array when the size is fixed at compile time.


Can a crate have multiple binaries?
✅ Yes. Use a src/bin/ folder with multiple .rs files—each compiles into a separate binary.


Share Now :
Share

Rust Modules, Packages & Collections

Or Copy Link

CONTENTS
Scroll to Top