Rust Language

Rust Modules and Libraries: The Basics

This document explains how to create a library in Rust and utilize it from a main program. A simple example is provided to enhance understanding of modules.

Project Creation

First, create the main project and the library.

cargo new main_app
cargo new --lib utils

This will result in the following directory structure:

.
├── utils
│   ├── Cargo.toml
│   └── src
│       ├── lib.rs
│       └── math
│           ├── mod.rs
│           └── operations.rs
└── main_app
    ├── Cargo.toml
    └── src
        └── main.rs

Library Implementation

Define nested modules within the library (utils).

utils/src/lib.rs:

pub mod math;

utils/src/math/mod.rs:

pub mod operations;

utils/src/math/operations.rs:

pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

pub fn subtract(a: i32, b: i32) -> i32 {
    a - b
}

This library creates a module named math, which in turn contains a submodule called operations.

Utilizing the Library in the Main Project

To use utils in the main project (main_app), add the dependency.

Add the following to main_app/Cargo.toml:

[dependencies]
utils = { path = "../utils" }

Next, use utils in the main program (main_app/src/main.rs).

main_app/src/main.rs:

use utils::math::operations;

fn main() {
    let sum = operations::add(5, 3);
    let difference = operations::subtract(10, 4);
    println!("5 + 3 = {}", sum);
    println!("10 - 4 = {}", difference);
}

Execution

Execute with the following command:

cd main_app
cargo run

Output:

5 + 3 = 8
10 - 4 = 6

Summary

  • Create a library using cargo new --lib
  • Define nested modules using pub mod
  • Add dependencies by specifying the path in Cargo.toml
  • Call the library in the main program using use

This example provides a clear and concise demonstration of Rust modules and libraries.