Skip to content

Common Project Structure

Posted on:January 5, 2024 at 08:00 AM (2 min read)

Table of contents

Open Table of contents

Module per file

📂 foo
├─ 📂 src
│  ├─ 📄 utils.rs    # module
│  └─ 📄 main.rs
└─ 📦 Cargo.toml

utils.rs

pub fn hello() {
  println!("hello world!");
}

main.rs

mod utils;       // load modules
use utils;

fn main () {
  utils.hello(); // call functions from module
}

Module per folder

📂 foo
├─ 📂 src
│  │
│  ├─ 📂 utils
│  │  ├─ 📄 mod.rs     # module entry point
│  │  ├─ 📄 say.rs
│  │  └─ 📄 cast.rs
│  │
│  └─ 📄 main.rs
│
└─ 📦 Cargo.toml

mod.rs

pub mod say;        // declare public access to function (exports)

say.rs

pub fn hello() {    // 👈 make it public, or just pub(crate) for internal use.
  println!("hello world!");
}

cast.rs

use super::say      // load say
pub fn cast() {
  say.hello();      // use function
}

main.rs

mod utils;          // load module
use utils::say;     // using say

fn main() {
  say.hello();      // call the functions
}

Lib

Create lib using cargo init <package> --lib

cargo init bar --lib
📂 bar
├─ 📂 src
│  └─ 📄 lib.rs     # lib entrypoint
└─ 📦 Cargo.toml

lib.rs

pub fn hello() {
    println!("hello world!");
}

Using libs

[dependencies]
foo = { git="https://YOU_GITHUB_REPO_URL"}

Workspace

📂 workspace-example
│
├─ 🗂 utils
│  ├─ 📂 src
│  │  └─ 📄 lib.rs     # lib entrypoint.
│  └─ 📦 Cargo.toml
│
├─ 📂 foo
│  ├─ 📂 src
│  │  └─ 📄 main.rs    # app entrypoint.
│  └─ 📦 Cargo.toml
│
└─ 📦 Cargo.toml

foo/Cargo.toml

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

Cargo.toml

[workspace]
members = [
  "utils",
  "foo",
]