Run a specific module in a external file with Rust

CK CK 3788 
Created at  
571 0 0

In Rust, you can load and use modules defined in external files by following these steps:

 

1. Create a File Structure

Rust organizes modules based on file and directory structure. For example:

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

 

2. Define a Module in the External File

Create utils.rs and define your module:

// utils.rs
pub fn greet(name: &str) {
    println!("Hello, {}!", name);
}

 

3. Load the Module in main.rs

In your main.rs, use the mod keyword to declare the module and bring it into scope:

// main.rs
mod utils;

fn main() {
    utils::greet("Alice");
}

 

4. Using Submodules (Optional)

If you want to organize your code into submodules within a directory, the structure looks like this:

src/
├── main.rs
├── utils/
│   ├── mod.rs
│   └── math.rs

Define Submodule in mod.rs

// utils/mod.rs
pub mod math;

pub fn greet(name: &str) {
    println!("Hello, {}!", name);
}

Define Functionality in math.rs

// utils/math.rs
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

Load and Use Submodules in main.rs

// main.rs
mod utils;

fn main() {
    utils::greet("Alice");
    let sum = utils::math::add(3, 4);
    println!("Sum: {}", sum);
}

 

Key Points

  1. File Naming and Structure: Rust modules correspond to file and directory names.
    • mod utils; looks for utils.rs or utils/mod.rs in the same directory.
  2. pub Keyword: Functions and modules must be declared pub to make them accessible from outside their defining module.
  3. Cargo: Ensure your files are in the src directory if using Cargo for project management.

This approach allows you to split and organize your Rust code across multiple files while maintaining modularity and clarity.

Tags Rust External Module Rust Library Rust Module cargo Facebook X
Comments 0
Similar posts
  1. Rust Documentation
    315
  2. Rust Std misc
    375
  3. Rust Package Management Tool - cargo
    307
  4. Rust compilation unit - Crates
    254
  1. How do I implement a heap in Rust?
    685
  2. How do I implement a stack in Rust?
    771
  3. Rust-GPU-tools for interacting with various GPU APIs
    756
  4. Rust array is fixed size. Can I modify its content?
    586
  5. Rust Example for Array and Dyamic Element Management (aka Vector-based Element Management)
    624
  6. The || syntax in Rust - also known as a closure
    601
  7. Basic Rust Thread Example to Perform Concurrent Computation
    618
  8. Multi-threaded HLS Server in Rust
    773
  9. Question(?) Operator in Rust
    573
  10. Rust code example to access MySQL
    1,100
  11. Rust Compatibility
    726
  12. Rust Unsafe Operations
    369
  13. Rust Testing
    1,246
  14. Rust Std library types
    370
  15. Rust Error Handling
    350
  16. Rust Macro Rules
    1,525
  17. Rust mechanism for defining shared behavior across different types - Traits
    1,774
  18. Rust Scoping Rules - only accessible within the block of code
    1,075
  19. Rust Generics - Generalizing types and functionalities
    1,358
  20. Rust Attributes for conditional compilation, crate, lints, mark functions, macros
    318
  21. Rust Modules - Visivility, Struct Visibility, Use Declaration, super and self, File Hierarchy
    1,909
  22. Rust functions - Methods, Closures, Capturing
    1,210
  23. Rust Flow of Control - if/else, loop. while, for and range, match, if let, let-else, while let
    339
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    31
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    57
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    51
  4. How do I create animated background for Google Meet?
    23,210
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    273
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    104
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    170
  8. Array of arguments passed to script in PHP
    99
  9. Invalid Auction Storms in Ad Tech
    107
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    208
  11. The Two Clocks of Ad Server Architecture
    78
  12. Frequency Cap Architecture Overview
    527
  13. Collecting Proof-of-Play from 100,000 Screens
    153
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    303
  15. What is RedisVL?
    116
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    247
  17. TPU & GPU Cluster Management Tools
    258
  18. The Concept of Scaffolding in AI Agents
    245
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    598
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    268
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    354
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    207
  23. Machine Learning: Training vs. Ranking
    229
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    228
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    203
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    674
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    201
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    233