How to Structure a Rust Project Before It Becomes a Mess
Every programming language has a way to organize code as it grows. Python has packages and modules. Java has packages and Maven or Gradle. Node.js has packages and npm. Rust has crates and modules, managed by Cargo.
This is one of those topics that feels dry until the day you need it, and then you really need it. When the Task Manager project from earlier articles was a single file it was fine. A real production application might have tens of files and dozens of dependencies. Without a clear structure things fall apart fast.
This article covers how Rust thinks about code organization and how Cargo makes dependency management genuinely pleasant compared to most alternatives I have worked with.
1. Crates
A crate is the smallest unit of compilation in Rust. Every project you create with cargo new is a crate. There are two kinds:
- A binary crate has a
mainfunction and compiles to an executable. - A library crate has no
mainfunction and compiles to code other crates can use.
When you run cargo new my_project you get a binary crate. When you run cargo new my_library --lib you get a library crate. The difference is whether src/main.rs or src/lib.rs is the root.
A single Cargo project can have both. A common pattern is having src/main.rs as a thin wrapper that calls into code in src/lib.rs. This makes the library code testable independently from the binary entry point.
2. Modules
Modules let you split code into logical namespaces within a crate. The mod keyword creates a module:
i32 {
a + b
}
pub fn subtract(a: i32, b: i32) -> i32 {
a – b
}
}
fn main() {
println!("{}", math::add(3, 4));
println!("{}", math::subtract(10, 3));
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
mod math {
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
pub fn subtract(a: i32, b: i32) -> i32 {
a - b
}
}
fn main() {
println!("{}", math::add(3, 4));
println!("{}", math::subtract(10, 3));
}
mod math {
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
pub fn subtract(a: i32, b: i32) -> i32 {
a - b
}
}
fn main() {
println!("{}", math::add(3, 4));
println!("{}", math::subtract(10, 3));
}
Everything in a module is private by default. The pub keyword makes it accessible from outside. This is the opposite of Java where everything is public unless you say otherwise.
Modules can be nested:
f64 {
std::f64::consts::PI * self.radius * self.radius
}
}
}
}
fn main() {
let c = geometry::shapes::Circle { radius: 5.0 };
println!("Area: {:.2}", c.area());
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
mod geometry {
pub mod shapes {
pub struct Circle {
pub radius: f64,
}
impl Circle {
pub fn area(&self) -> f64 {
std::f64::consts::PI * self.radius * self.radius
}
}
}
}
fn main() {
let c = geometry::shapes::Circle { radius: 5.0 };
println!("Area: {:.2}", c.area());
}
mod geometry {
pub mod shapes {
pub struct Circle {
pub radius: f64,
}
impl Circle {
pub fn area(&self) -> f64 {
std::f64::consts::PI * self.radius * self.radius
}
}
}
}
fn main() {
let c = geometry::shapes::Circle { radius: 5.0 };
println!("Area: {:.2}", c.area());
}
3. The use Keyword
Typing full paths every time gets tedious. use brings names into the current scope:
use geometry::shapes::Circle;
fn main() {
let c = Circle { radius: 3.0 };
println!("{:.2}", c.area());
}
use geometry::shapes::Circle;
fn main() {
let c = Circle { radius: 3.0 };
println!("{:.2}", c.area());
}
You can bring in multiple items with curly braces:
use std::collections::{HashMap, HashSet, BTreeMap};
use std::collections::{HashMap, HashSet, BTreeMap};
Or everything from a module with the glob operator (though this is generally discouraged in application code because it is unclear where names come from):
use std::collections::*; // not recommended in most cases
use std::collections::*; // not recommended in most cases
If two names conflict, you can use as to rename one:
use std::fmt::Result;
use std::io::Result as IoResult;
use std::fmt::Result;
use std::io::Result as IoResult;
4. Splitting into Multiple Files
When a module gets large you move it to its own file. There are two conventions Rust supports.
The old style: put module code in a file named after the module:
src/
main.rs
math.rs ← content of the math module
src/
main.rs
math.rs ← content of the math module
In main.rs:
mod math; // tells the compiler to look for math.rs
fn main() {
println!("{}", math::add(3, 4));
}
mod math; // tells the compiler to look for math.rs
fn main() {
println!("{}", math::add(3, 4));
}
In math.rs:
i32 {
a + b
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-1/2 -translate-y-1/2 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
The new style uses a directory with a mod.rs file, or a directory with the module’s content directly. For nested modules:
src/
main.rs
geometry/
mod.rs ← or geometry.rs at the src level
shapes.rs
src/
main.rs
geometry/
mod.rs ← or geometry.rs at the src level
shapes.rs
For larger projects the directory approach keeps things organized as sub-modules grow.
5. A Real Project Structure
Here is what a production-level Rust project typically looks like:
my_app/
├── Cargo.toml
├── Cargo.lock
├── src/
│ ├── main.rs ← binary entry point, minimal code
│ ├── lib.rs ← library root, re-exports public API
│ ├── config.rs ← configuration loading
│ ├── error.rs ← custom error types
│ ├── models/
│ │ ├── mod.rs
│ │ ├── user.rs
│ │ └── task.rs
│ └── handlers/
│ ├── mod.rs
│ ├── auth.rs
│ └── tasks.rs
├── tests/
│ └── integration_test.rs ← integration tests
└── examples/
└── basic_usage.rs ← runnable examples
my_app/
├── Cargo.toml
├── Cargo.lock
├── src/
│ ├── main.rs ← binary entry point, minimal code
│ ├── lib.rs ← library root, re-exports public API
│ ├── config.rs ← configuration loading
│ ├── error.rs ← custom error types
│ ├── models/
│ │ ├── mod.rs
│ │ ├── user.rs
│ │ └── task.rs
│ └── handlers/
│ ├── mod.rs
│ ├── auth.rs
│ └── tasks.rs
├── tests/
│ └── integration_test.rs ← integration tests
└── examples/
└── basic_usage.rs ← runnable examples
The main.rs stays small:
// main.rs
use my_app::run;
fn main() {
if let Err(e) = run() {
eprintln!("Error: {}", e);
std::process::exit(1);
}
}
// main.rs
use my_app::run;
fn main() {
if let Err(e) = run() {
eprintln!("Error: {}", e);
std::process::exit(1);
}
}
The lib.rs is where everything lives:
Result {
// application logic
Ok(())
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
// lib.rs
mod config;
mod error;
pub mod models;
pub mod handlers;
pub use error::AppError;
pub fn run() -> Result<(), AppError> {
// application logic
Ok(())
}
// lib.rs
mod config;
mod error;
pub mod models;
pub mod handlers;
pub use error::AppError;
pub fn run() -> Result<(), AppError> {
// application logic
Ok(())
}
This pattern means the entire application logic is testable through the library interface. The binary just calls run().
6. Cargo.toml and Dependencies
The Cargo.toml file is where you declare what your project is and what it depends on:
<button data-code="[package]
name = "my_app"
version = "0.1.0"
edition = "2021"
description = "A task management application"
authors = ["Your Name "]
[dependencies]
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["full"] }
anyhow = "1"
clap = { version = "4", features = ["derive"] }
[dev-dependencies]
tempfile = "3"
[build-dependencies]
# dependencies only used during build scripts” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
[package]
name = "my_app"
version = "0.1.0"
edition = "2021"
description = "A task management application"
authors = ["Your Name <[email protected]>"]
[dependencies]
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["full"] }
anyhow = "1"
clap = { version = "4", features = ["derive"] }
[dev-dependencies]
tempfile = "3"
[build-dependencies]
# dependencies only used during build scripts
[package]
name = "my_app"
version = "0.1.0"
edition = "2021"
description = "A task management application"
authors = ["Your Name <[email protected]>"]
[dependencies]
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["full"] }
anyhow = "1"
clap = { version = "4", features = ["derive"] }
[dev-dependencies]
tempfile = "3"
[build-dependencies]
# dependencies only used during build scripts
[dev-dependencies] are only compiled when running tests or examples. They are not included in the final binary.
Run cargo add serde to add a dependency without editing the file manually. Run cargo update to update to newer compatible versions. The Cargo.lock file records exact versions for reproducible builds.
7. Visibility Rules in Depth
Understanding visibility saves a lot of confusion:
mod outer {
pub mod inner {
pub fn public_fn() {}
fn private_fn() {} // only accessible within inner
}
fn can_call_inner() {
inner::public_fn(); // fine
// inner::private_fn(); // ERROR
}
}
fn main() {
outer::inner::public_fn(); // fine
// outer::can_call_inner(); // ERROR: can_call_inner is private
}
mod outer {
pub mod inner {
pub fn public_fn() {}
fn private_fn() {} // only accessible within inner
}
fn can_call_inner() {
inner::public_fn(); // fine
// inner::private_fn(); // ERROR
}
}
fn main() {
outer::inner::public_fn(); // fine
// outer::can_call_inner(); // ERROR: can_call_inner is private
}
A useful visibility modifier is pub(crate). It makes something public within the current crate but not to external code:
pub(crate) struct InternalConfig {
pub(crate) debug_mode: bool,
}
pub(crate) struct InternalConfig {
pub(crate) debug_mode: bool,
}
This is more restrictive than pub (which exposes to everyone) and less restrictive than private (which only allows the same module). In Java the equivalent is package-private access, but Rust’s version is more explicit.
8. Common Crates Worth Knowing
Part of learning Rust is learning the ecosystem. These are crates that come up in almost every serious project:
serde for serialization and deserialization. JSON, TOML, YAML, CSV, you name it. Nearly everything uses serde.
tokio for async runtime. You already know this one.
anyhow for easy error handling in applications. Instead of defining custom error types for every function, anyhow::Result accepts any error.
thiserror for defining custom error types cleanly. Where anyhow is for applications, thiserror is for libraries.
clap for command-line argument parsing. Used in almost every CLI tool.
reqwest for HTTP clients. Async, built on tokio, handles everything from simple GET requests to multipart uploads.
sqlx for database access. Type-safe SQL queries checked at compile time.
tracing for structured logging and diagnostics.
[dependencies]
anyhow = "1"
thiserror = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["full"] }
reqwest = { version = "0.11", features = ["json"] }
clap = { version = "4", features = ["derive"] }
tracing = "0.1"
tracing-subscriber = "0.3"
[dependencies]
anyhow = "1"
thiserror = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["full"] }
reqwest = { version = "0.11", features = ["json"] }
clap = { version = "4", features = ["derive"] }
tracing = "0.1"
tracing-subscriber = "0.3"
This is a fairly complete starting stack for a web service or a CLI tool with network calls.
9. Workspaces
When a project gets large enough to split into multiple related crates, Cargo workspaces let you manage them together:
# Cargo.toml at the workspace root
[workspace]
members = [
"core",
"api",
"cli",
]
# Cargo.toml at the workspace root
[workspace]
members = [
"core",
"api",
"cli",
]
Each member is its own crate with its own Cargo.toml. They share a single Cargo.lock and a single target directory. Running cargo build at the workspace root builds all members. Running cargo test runs tests across all of them.
This is the pattern used by large Rust projects like Tokio itself and most production-grade Rust applications.
Summary
Crates are the compilation unit. Modules organize code within a crate. pub controls what is visible outside a module. Files and directories map directly to module paths. Cargo.toml declares dependencies and Cargo.lock locks exact versions. Learning the ecosystem crates saves you from reinventing wheels that the community has already made very well.
What’s Next
Testing in Rust. Unit tests, integration tests, property-based testing. Rust has testing built into the language and cargo, which means the workflow is cleaner than most other languages I have worked in.
Happy coding and safe assembling!
Follow this series and join us in mastering Rust from scratch!


