Organizing Rust Projects as They Grow Into Workspaces
How to structure a Rust codebase as it grows: modules, a lib and bin split, workspaces, layers and the boundaries that keep compile times and coupling in check.

Every Rust project starts as one main.rs, and most of them are better for it. Then a file reaches 2,000 lines, a second binary appears, someone wants to reuse the parsing code in a web service, and the question arrives: how should this be organized? There are three tools, modules, crates and workspaces, and the common mistake is reaching for the heaviest one first. This guide walks the growth path in order, shows what each step costs and buys with a real multi-crate workspace, and ends with the rules that keep a large repository from turning into a tangle.
The workspace in the examples was built and run on Rust 1.99 (edition 2024) with the resolver at version 3. The three-crate shop used throughout is small on purpose, because the structure is what matters, and the outputs are what Cargo printed.
Three levels of structure
Rust gives you three units, and each answers a different question.
| Unit | What it is | Use it to |
|---|---|---|
| Module | A namespace inside a crate, a file or inline mod | Organize code and control visibility within one compilation unit |
| Crate | One compilation unit, a library or a binary | Set a boundary the compiler enforces, share code, build in parallel |
| Workspace | A set of crates built together with one lockfile | Develop several related crates in one repository |
A module is free: it costs nothing at compile time, and moving a function between modules is a refactor, not a design decision. A crate boundary costs something: items crossing it must be pub, the public surface is a commitment, and the compiler treats the crate as a unit of incremental compilation. A workspace adds a place to keep the crates together, one Cargo.lock, one target directory and shared settings.
The rule that follows: use modules until you have a reason to use a crate, and use a crate until you have several of them in one repository.
Stage one: modules inside one crate
A single crate can grow large without any trouble. The standard layout for a binary that has outgrown one file looks like this:
src/
main.rs thin: parse arguments, call into the library
lib.rs declares the modules and the public API
config.rs
parser/
mod.rs or parser.rs next to a parser/ directory
tokens.rs
grammar.rs
store.rsPutting the logic in lib.rs and keeping main.rs thin is the single most useful structural habit, even for a one-crate project. Integration tests in tests/ can only call a library, so logic in main.rs cannot be tested from outside; and a second binary, a benchmark or an example can reuse the library without copying anything. Since Rust 2018 a module can live in parser.rs with its children in parser/tokens.rs, which keeps the directory listing free of dozens of files named mod.rs.
Visibility is the tool that makes modules worth having. Items are private by default, and pub(crate) makes them visible across the crate without exposing them to users of the library. A good module has a small public surface, a few pub functions and types, and keeps everything else private. When a change inside the module does not break the rest of the crate, the module boundary is doing its job. If everything is pub everywhere, the modules are decoration.
When one crate stops being enough
Four situations push you to split a crate. They are worth distinguishing, because the right split differs.
You need a second consumer. A command line tool and a web service both need the same domain logic. The domain code belongs in a library crate that both depend on, and neither application owns it.
Compile times hurt. Cargo compiles each crate as a unit and compiles independent crates in parallel. A 60,000-line crate recompiles from its first changed line to its end, while the same code split into six crates only recompiles the changed crate and those that depend on it. This is real, and it is also overstated: splitting a project that compiles in 20 seconds buys little, and the biggest compile-time wins usually come from trimming dependencies and features, not from more crates.
You want a boundary the compiler enforces. Inside a crate, any module can call any other module's pub(crate) items, so layering rules live on trust. Across crates, a dependency is declared in Cargo.toml and visible, and an accidental call upward in the layers is a missing-dependency error. This is the best reason to split, and the one least often given.
Part of the code has different build requirements: a proc-macro crate must be its own crate, a crate that must be no_std, a crate that wraps a C library with a build script that you do not want to rerun, or a crate you intend to publish while the rest stays private.
Stage two: a workspace
A workspace is a root Cargo.toml that lists member crates. This is the one used here, with three crates, a core library of types and rules, a storage layer that depends on it, and a command line binary that uses both:
[workspace]
resolver = "3"
members = ["crates/*"]
[workspace.package]
version = "0.1.0"
edition = "2024"
license = "MIT"
rust-version = "1.85"
[workspace.dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2"
shop-core = { path = "crates/shop-core" }
shop-store = { path = "crates/shop-store" }
[workspace.lints.rust]
unsafe_code = "forbid"
[workspace.lints.clippy]
unwrap_used = "warn"Each part of this file earns its place. members = ["crates/*"] picks up every directory under crates/, so adding a crate means creating a directory. [workspace.package] holds values shared by every member, and [workspace.dependencies] pins each dependency's version once for the whole repository, so two crates cannot drift to different versions of serde. The internal crates appear there too, as path dependencies, which gives members a short way to refer to each other. And [workspace.lints] sets rules for every crate in one place.
A member manifest then inherits instead of repeating:
[package]
name = "shop-store"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[lints]
workspace = true
[dependencies]
shop-core.workspace = true
serde_json.workspace = trueversion.workspace = true and the other inherited fields mean a version bump or edition change is one edit. shop-core.workspace = true in the dependencies reads as "the workspace's definition of shop-core", which resolves to the path. Everything else about the crate, its code, its tests and its own dependencies, is unchanged.
The dependency direction
The crates form a graph, and the graph is the architecture:
$ cargo tree -p shop-cli --depth 1
shop-cli v0.1.0 (crates/shop-cli)
├── shop-core v0.1.0 (crates/shop-core)
└── shop-store v0.1.0 (crates/shop-store)shop-core has no dependency on the others, shop-store depends on shop-core, and shop-cli depends on both. Arrows point from the application toward the foundation, never back. Cargo enforces the rule with a hard error. If someone adds shop-store as a dependency of shop-core to reach a convenience function, Cargo refuses:
error: cyclic package dependency: package `shop-core v0.1.0` depends on itself. Cycle:
package `shop-core v0.1.0`
... which satisfies path dependency `shop-core` (locked to 0.1.0) of package `shop-store v0.1.0`
... which satisfies path dependency `shop-store` (locked to 0.1.0) of package `shop-core v0.1.0`That error is the architecture review you did not have to schedule. The foundation crate cannot know about the layers above it. The fix is never to break the rule: move the shared piece down into shop-core, or into a new crate that both depend on. A repository where cycles are impossible stays understandable as it grows.
What rebuilds when you change something
The reason to split shows in the build output. Touching a file in shop-core, the foundation, rebuilds everything that depends on it:
$ touch crates/shop-core/src/lib.rs && cargo build
Compiling shop-core v0.1.0 (crates/shop-core)
Compiling shop-store v0.1.0 (crates/shop-store)
Compiling shop-cli v0.1.0 (crates/shop-cli)Touching the binary rebuilds only the binary:
$ touch crates/shop-cli/src/main.rs && cargo build
Compiling shop-cli v0.1.0 (crates/shop-cli)The consequence for design is that the crates at the bottom should be the most stable, the ones you change least, because every change to them recompiles the whole tree above. Put volatile code, the application glue and the product-specific logic, at the top. If the core crate changes daily, the split buys you nothing on rebuild time, and that is a signal it has the wrong contents.
One set of rules for every crate
Shared lint settings are the quiet benefit of a workspace. The root manifest above forbids unsafe and warns on unwrap, and each member opts in with [lints] workspace = true. Add an unsafe block anywhere and the compiler refuses:
error: usage of an `unsafe` block
--> crates/shop-store/src/lib.rs:7:32
|
7 | pub fn first(v: &[u8]) -> u8 { unsafe { *v.get_unchecked(0) } }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: requested on the command line with `-F unsafe-code`And cargo clippy --workspace reports unwrap() on a Result in any crate:
warning: used `unwrap()` on a `Result` value
--> crates/shop-store/src/lib.rs:7:32
|
7 | pub fn parse(s: &str) -> u32 { s.parse().unwrap() }The forbid level cannot be overridden by a local #[allow], which is the point: the policy is a repository decision, not a per-file one. If one crate needs unsafe, such as a binding crate, leave it out of the lint inheritance and give it its own [lints] table, which makes the exception visible in review.
The feature trap that only appears in a workspace
Features unify, which means the set of features compiled for a crate is the union of what everyone who selected it asked for. In a workspace that has a visible consequence, and it is worth seeing once. Give shop-core an optional feature pretty that adds a describe function, and let only shop-cli enable it in its dependency line: shop-core = { workspace = true, features = ["pretty"] }. Now ask Cargo what gets built, first for the storage crate alone and then for the whole workspace:
$ cargo tree -p shop-store -e features --depth 1
shop-store v0.1.0 (crates/shop-store)
├── serde_json feature "default"
└── shop-core feature "default"
$ cargo tree --workspace -e features --depth 1
shop-cli v0.1.0 (crates/shop-cli)
├── shop-core feature "default" (command-line)
├── shop-core feature "pretty"Building shop-store on its own compiles shop-core without pretty. Building the whole workspace compiles shop-core once, with pretty on, and shop-store sees that version. If shop-store accidentally calls describe, it compiles in a workspace build and fails in cargo build -p shop-store, and the same crate fails differently on a downstream user's machine, where only the features they selected exist. The edition 2024 resolver keeps unification limited to the packages you actually select, which is better than the old behavior, and the discipline that goes with it is simple: every crate must declare, in its own manifest, every feature of its dependencies that it uses. CI should catch the cases you forget. Run cargo check -p <crate> for each member separately as well as cargo check --workspace. The cargo hack tool automates this: cargo hack check --each-feature --workspace builds every crate with each feature turned on alone and reports the combination that breaks.
Moving code between crates, guided by the compiler
Reorganizing a codebase is easier in Rust than in most languages, because the compiler lists every place the change touches. The procedure for lifting a module into its own crate has five steps, and each ends in either a clean build or an error list that tells you the next edit.
- Create the crate with
cargo new --lib crates/shop-pricingand add it to the workspace dependencies. Becausemembersis a glob, it is already a member. - Move the module's files into the new crate's
src/and make its public itemspub. Everything that waspub(crate)and is used from outside now needs to bepub, and the compiler's "private item" errors enumerate exactly which ones. - In the old crate, depend on the new one and
pub use shop_pricing::*;or fix theusepaths. The re-export keeps existing callers compiling while you migrate them. - Build the workspace. Missing dependencies in the new crate show as "unresolved import" errors; add them to its manifest from
[workspace.dependencies]. - Delete the re-export once the callers use the new path, and run the whole test suite.
Do this in small commits, one module at a time. The mechanical errors are almost all one of four kinds: a private item that needs pub, a missing dependency, a path that changed, and a trait implementation that now violates the orphan rule because the type and trait ended up in different crates. The last is the one that needs thought. It is the reason core types and the traits that describe them belong together, in the lowest crate in the graph.
Tasks that are not Cargo commands: xtask
Every repository grows scripts: generate the schema, bundle the front end, run the end-to-end suite. Shell scripts work until a Windows contributor appears. The xtask convention puts them in a workspace member, a binary crate named xtask, and an alias in .cargo/config.toml makes cargo xtask <command> run it.
[alias]
xtask = "run --package xtask --"Because the tasks are Rust, they share the repository's dependencies and run on every platform, and a contributor needs only the toolchain they already installed. Keep xtask small; it is a convenience, not a second build system. A good test of whether a task belongs there is whether it needs knowledge of the workspace's crates, as a release helper or a code generator does. If it only needs bash, a script is fine.
Testing and CI in a workspace
Running everything on every change does not scale past a certain size, and the workspace gives you the information to avoid it. cargo metadata describes the dependency graph, so a CI job can test only the crates affected by a change: the changed crates and everything that depends on them. Tools exist for this, and a small script over cargo metadata --format-version 1 is enough to start. Two other settings keep CI fast. A shared target directory cache keyed on Cargo.lock means unchanged dependencies are not recompiled, and cargo test --workspace --no-run followed by running the test binaries in parallel jobs separates compilation from execution. Keep a separate, slower job that runs the full suite with --all-features and again with --no-default-features; these two catch the features trap from earlier before a downstream user does.
Commands that work across the workspace
Cargo's package selection flags make the workspace pleasant to drive:
cargo build # all default members
cargo test --workspace # every member's tests
cargo test -p shop-core # one crate
cargo run -p shop-cli # a binary by package name
cargo clippy --workspace --all-targets
cargo build --workspace --exclude shop-cli
cargo tree --duplicates # find two versions of the same dependencycargo test --workspace ran the tests of all three crates and their doctests, in one invocation with one lockfile and one shared compilation cache. The cargo tree --duplicates command lists dependencies compiled in more than one version, which is the first place to look when build times or binary sizes surprise you. To make cargo build at the root skip a heavy crate by default, list default-members in the workspace table.
Features: the other way to organize
A crate split is not the only way to make optional code optional. Cargo features gate code and dependencies inside one crate: [features] postgres = ["dep:sqlx"] and #[cfg(feature = "postgres")] on the code that needs it. Features suit optional integrations on a library; separate crates suit layers with different stability. A word of caution on features: they are additive and unify across the dependency graph, so if any crate in your build enables a feature, it is on for all. Design features so that enabling one never breaks code that does not use it, and set resolver = "3" (the default for edition 2024) so that feature unification behaves predictably across targets.
Rules of thumb for a growing repository
- Name crates for what they are, with a shared prefix:
shop-core,shop-store. A flatcrates/directory scales to dozens. - Keep the dependency graph a layered tree. A diagram of arrows that cross in the middle is a design warning.
- Make the binary crates thin. The code that matters lives in libraries, where tests, benchmarks and other binaries can reach it.
- Pin versions in one place, with
[workspace.dependencies], and review additions there as the supply-chain gate. - Put test utilities in a
dev-dependencies-only crate (shop-testkit) instead of copying fixtures between crates. - Publish deliberately. Mark internal crates
publish = falseso that a straycargo publishcannot release them. - Add a crate when you can finish the sentence "this crate exists so that ...". "Because the folder was getting big" is a module.
When not to split
Do not split a project whose entire code compiles in a few seconds and has one consumer. Do not create a crate for each layer of a hexagonal diagram on day one; start with modules and split along the seams that hurt. Do not split to chase compile times without measuring: cargo build --timings shows which crates are on the critical path, and often the slow part is a dependency or a build script, which splitting your code does not touch. And if you need to share code between repositories, a workspace is the wrong tool; publish a crate, or use a git dependency pinned to a revision. For the tools that make large repositories pleasant, see Cargo release profile settings and continuous integration for Rust.


