Programming languages · Advanced · 22 min
Split a Rust project into a Cargo workspace
By Padding · Updated 18 Nov 2026
Debian 13 (rust:1.100 image) · Rust 1.100.0 · Cargo 1.100.0
You will turn a single-crate Rust tool into a Cargo workspace with a core library, a CLI binary and a shared test-utils crate, all built, tested and versioned from one root manifest.
On this page
Most Rust projects start as one crate: a Cargo.toml, a src/main.rs, and code that grows until the file is long and every change rebuilds everything. A Cargo workspace is a set of crates that live in one repository and share one Cargo.lock and one target directory. Each crate keeps its own manifest, its own dependencies and its own public interface, but you build and test them together with one command.
In this tutorial you build tally, a small tool that counts the lines, words and characters in a text file and reports the most common word. You write it first as a single crate, then split it into three:
tally-core, a library with the counting logic and an optionaljsonfeaturetally-cli, the binary people run, which depends on the librarytally-test-utils, shared fixtures that only the tests use, never published
Along the way you set up inheritance from the root manifest, path dependencies between crates, per-crate builds with -p, workspace-wide tests, and pub(crate) for code the library keeps to itself. The last step covers when a workspace is more structure than a project needs. Everything was written for Rust 1.100.0 and the 2024 edition; any Rust from 1.85 onwards builds it.
Step 1 · Build the tool as a single crate
Create the project in a throwaway folder. --vcs none skips creating a Git repository, so you can drop the folder at the end without thinking about it:
cargo new --vcs none ~/tally-demo --name tally
cd ~/tally-demoReplace src/main.rs with the whole tool in one file:
cat > src/main.rs <<'RS'
use std::collections::HashMap;
use std::{env, fs, process::ExitCode};
fn split_words(text: &str) -> impl Iterator<Item = String> {
text.split_whitespace()
.map(|w| w.trim_matches(|c: char| !c.is_alphanumeric()).to_lowercase())
.filter(|w| !w.is_empty())
}
fn main() -> ExitCode {
let Some(path) = env::args().nth(1) else {
eprintln!("usage: tally <file>");
return ExitCode::from(2);
};
let text = match fs::read_to_string(&path) {
Ok(text) => text,
Err(err) => {
eprintln!("cannot read {path}: {err}");
return ExitCode::FAILURE;
}
};
let lines = text.lines().count();
let words = split_words(&text).count();
let chars = text.chars().count();
println!("lines={lines} words={words} chars={chars}");
let mut seen: HashMap<String, usize> = HashMap::new();
for word in split_words(&text) {
*seen.entry(word).or_default() += 1;
}
if let Some((word, n)) = seen
.into_iter()
.max_by(|a, b| a.1.cmp(&b.1).then_with(|| b.0.cmp(&a.0)))
{
println!("top={word} ({n})");
}
ExitCode::SUCCESS
}
RSsplit_words lowercases each word and trims punctuation from both ends, so The and the count as one word. When two words tie, the one that sorts first alphabetically wins, so the output is the same on every run even though HashMap order is random.
Make a sample file and run the tool:
printf 'The cat sat.\non the mat\n' > sample.txt
cargo run --quiet -- sample.txtCheck it worked
The output is two lines: lines=2 words=6 chars=24 and top=the (2). The character count includes both newlines. Rust's chars() counts Unicode scalar values, not bytes, so a word such as café counts as four characters even though it takes five bytes. Text in Yoruba or Vietnamese written with combining tone marks counts each mark separately.
Step 2 · Write the root manifest and the core library
Everything in main.rs mixes two jobs: counting text, and talking to the terminal. The counting part is what other programs (a web service, a test, a second tool) would want to reuse, so it becomes a library.
The next command deletes the single crate's Cargo.toml and src folder. You rewrite both below; sample.txt, Cargo.lock and target stay.
cd ~/tally-demo
rm -r src Cargo.toml
mkdir -p crates/tally-core/srcThe root Cargo.toml now describes the workspace and has no [package] of its own. Cargo calls this a virtual manifest:
cat > Cargo.toml <<'TOML'
[workspace]
resolver = "3"
members = ["crates/*"]
[workspace.package]
version = "0.1.0"
edition = "2024"
rust-version = "1.85"
[workspace.dependencies]
thiserror = "2"
TOMLWhat each table does:
members = ["crates/*"]makes every folder undercrates/with aCargo.tomlpart of the workspace. New crates join by being created there.resolver = "3"picks the dependency resolver. Edition 2024 packages use it by default, but a virtual manifest has no edition, so you set it here. Version 3 prefers dependency versions that support yourrust-version.[workspace.package]holds fields that members can inherit, so the version and edition live in one place.[workspace.dependencies]pins third-party crates once. Members opt in by name, and every crate gets the same version.
Now the library's manifest. Each .workspace = true line pulls its value from the root:
cat > crates/tally-core/Cargo.toml <<'TOML'
[package]
name = "tally-core"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
[dependencies]
thiserror.workspace = true
TOMLThe library code is the counting logic from main.rs, with a proper error type instead of printing and returning early:
cat > crates/tally-core/src/lib.rs <<'RS'
//! Counting logic for the tally tool.
use std::collections::HashMap;
/// Line, word and character counts for one piece of text.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Counts {
pub lines: usize,
pub words: usize,
pub chars: usize,
}
/// Why a piece of text could not be counted.
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
pub enum CountError {
#[error("the text is empty")]
Empty,
}
/// Counts lines, words and characters. Blank text is an error.
pub fn count(text: &str) -> Result<Counts, CountError> {
if text.trim().is_empty() {
return Err(CountError::Empty);
}
Ok(Counts {
lines: text.lines().count(),
words: split_words(text).count(),
chars: text.chars().count(),
})
}
/// The most common word and how often it appears. Ties go to the
/// word that sorts first.
pub fn top_word(text: &str) -> Option<(String, usize)> {
let mut seen: HashMap<String, usize> = HashMap::new();
for word in split_words(text) {
*seen.entry(word).or_default() += 1;
}
seen.into_iter()
.max_by(|a, b| a.1.cmp(&b.1).then_with(|| b.0.cmp(&a.0)))
}
/// How the crate turns text into words. Visible inside tally-core only.
pub(crate) fn split_words(text: &str) -> impl Iterator<Item = String> {
text.split_whitespace()
.map(|w| w.trim_matches(|c: char| !c.is_alphanumeric()).to_lowercase())
.filter(|w| !w.is_empty())
}
#[cfg(test)]
mod tests {
use super::split_words;
#[test]
fn split_words_trims_punctuation_and_case() {
let words: Vec<String> = split_words("Hello, World!").collect();
assert_eq!(words, ["hello", "world"]);
}
}
RSsplit_words is marked pub(crate). Code anywhere inside tally-core can call it, including the unit test at the bottom, but other crates cannot. That keeps the word-splitting rule an internal detail you can change without breaking anyone. count, top_word, Counts and CountError are pub, and they are the library's whole interface.
Build only the library with -p (short for --package):
cargo build -p tally-coreCheck it worked
Cargo downloads thiserror and its dependencies the first time, then prints Compiling lines for them and for tally-core v0.1.0 (.../tally-demo/crates/tally-core), ending with Finished. Nothing called tally is built, because no binary crate exists yet.
Step 3 · Add a shared test-utils crate
Tests in several crates will want the same sample text and the same way of writing a temporary file. Rather than copying those helpers, put them in a crate of their own. publish = false stops anyone uploading it to crates.io by accident:
mkdir -p crates/tally-test-utils/src
cat > crates/tally-test-utils/Cargo.toml <<'TOML'
[package]
name = "tally-test-utils"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
publish = false
TOML
cat > crates/tally-test-utils/src/lib.rs <<'RS'
//! Fixtures shared by the tests in this workspace. Not published.
use std::fs;
use std::path::PathBuf;
/// Two lines, six words, 24 characters; "the" appears twice.
pub const SAMPLE: &str = "The cat sat.\non the mat\n";
/// Writes `contents` to a file in the system temp folder and returns its path.
pub fn write_temp(name: &str, contents: &str) -> PathBuf {
let path = std::env::temp_dir().join(format!("tally-{}-{name}", std::process::id()));
fs::write(&path, contents).expect("write temp file");
path
}
RSThe library uses it only in tests, so it goes under [dev-dependencies]. A path dependency points at the other crate's folder, relative to the manifest that names it:
cat >> crates/tally-core/Cargo.toml <<'TOML'
[dev-dependencies]
tally-test-utils = { path = "../tally-test-utils" }
TOMLAdd integration tests for the library. Files in a crate's tests/ folder are compiled as separate programs that use the crate from outside, exactly as another crate would, so they see only pub items:
mkdir -p crates/tally-core/tests
cat > crates/tally-core/tests/counts.rs <<'RS'
use tally_core::{count, top_word, CountError, Counts};
use tally_test_utils::SAMPLE;
#[test]
fn counts_the_sample() {
let expected = Counts { lines: 2, words: 6, chars: 24 };
assert_eq!(count(SAMPLE), Ok(expected));
}
#[test]
fn blank_text_is_an_error() {
assert_eq!(count(" \n"), Err(CountError::Empty));
}
#[test]
fn top_word_ignores_case_and_punctuation() {
assert_eq!(top_word(SAMPLE), Some(("the".to_string(), 2)));
}
RS
cargo test -p tally-coreCrate names use hyphens in Cargo.toml and underscores in code: tally-test-utils is imported as tally_test_utils.
Check it worked
Cargo runs three groups: the unit test in src/lib.rs (1 passed), the integration tests in tests/counts.rs (3 passed) and the doc-tests (0 tests, as the docs have no code examples). Each group ends with test result: ok. and 0 failed.
Step 4 · Put optional code behind a feature
A feature is a named switch in a library that turns extra code on at compile time. Users who do not ask for it never compile it. Add a json feature that gives Counts a to_json method. The method writes the JSON by hand, so the feature adds no dependencies:
cat >> crates/tally-core/Cargo.toml <<'TOML'
[features]
default = []
json = []
TOML
cat >> crates/tally-core/src/lib.rs <<'RS'
#[cfg(feature = "json")]
impl Counts {
/// The counts as a JSON object. Built only with the `json` feature.
pub fn to_json(&self) -> String {
format!(
r#"{{"lines":{},"words":{},"chars":{}}}"#,
self.lines, self.words, self.chars
)
}
}
#[cfg(all(test, feature = "json"))]
mod json_tests {
use super::count;
#[test]
fn to_json_writes_an_object() {
let counts = count("hi yo").unwrap();
assert_eq!(counts.to_json(), r#"{"lines":1,"words":2,"chars":5}"#);
}
}
RSdefault = [] means the feature is off unless someone asks for it. List the unit tests with and without the feature:
cargo test -q -p tally-core --lib -- --list
cargo test -q -p tally-core --lib --features json -- --listCheck it worked
The first list has one test, tests::split_words_trims_punctuation_and_case. The second has two: the same one plus json_tests::to_json_writes_an_object. Run cargo test -p tally-core --features json to see the new test pass.
Step 5 · Add the CLI crate on top of the library
The binary is now a thin layer: read arguments, read the file, call the library, print. Its package is called tally-cli, and the [[bin]] table names the program people type, tally. It turns on the library's json feature in its dependency line:
mkdir -p crates/tally-cli/src crates/tally-cli/tests
cat > crates/tally-cli/Cargo.toml <<'TOML'
[package]
name = "tally-cli"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
[[bin]]
name = "tally"
path = "src/main.rs"
[dependencies]
tally-core = { path = "../tally-core", features = ["json"] }
thiserror.workspace = true
[dev-dependencies]
tally-test-utils = { path = "../tally-test-utils" }
TOMLThe CLI has its own error type. #[from] lets ? turn the library's CountError into a CliError with no extra code:
cat > crates/tally-cli/src/main.rs <<'RS'
use std::{env, fs, process::ExitCode};
use tally_core::{count, top_word, CountError};
#[derive(Debug, thiserror::Error)]
enum CliError {
#[error("usage: tally [--json] <file>")]
Usage,
#[error("cannot read {path}: {source}")]
Read { path: String, source: std::io::Error },
#[error(transparent)]
Count(#[from] CountError),
}
fn run() -> Result<(), CliError> {
let mut json = false;
let mut path = None;
for arg in env::args().skip(1) {
if arg == "--json" {
json = true;
} else if path.is_none() {
path = Some(arg);
} else {
return Err(CliError::Usage);
}
}
let path = path.ok_or(CliError::Usage)?;
let text = fs::read_to_string(&path)
.map_err(|source| CliError::Read { path: path.clone(), source })?;
let counts = count(&text)?;
if json {
println!("{}", counts.to_json());
} else {
println!("lines={} words={} chars={}", counts.lines, counts.words, counts.chars);
if let Some((word, n)) = top_word(&text) {
println!("top={word} ({n})");
}
}
Ok(())
}
fn main() -> ExitCode {
match run() {
Ok(()) => ExitCode::SUCCESS,
Err(err) => {
eprintln!("tally: {err}");
ExitCode::FAILURE
}
}
}
RSAdd tests that run the real binary. Cargo sets CARGO_BIN_EXE_tally to its path while it builds the crate's integration tests, so the test never has to guess where the build put it:
cat > crates/tally-cli/tests/cli.rs <<'RS'
use std::process::Command;
use tally_test_utils::{write_temp, SAMPLE};
fn tally(args: &[&str]) -> std::process::Output {
Command::new(env!("CARGO_BIN_EXE_tally"))
.args(args)
.output()
.expect("run tally")
}
#[test]
fn prints_counts_and_top_word() {
let path = write_temp("plain.txt", SAMPLE);
let out = tally(&[path.to_str().unwrap()]);
assert!(out.status.success());
let stdout = String::from_utf8(out.stdout).unwrap();
assert_eq!(stdout, "lines=2 words=6 chars=24\ntop=the (2)\n");
}
#[test]
fn json_flag_prints_one_object() {
let path = write_temp("json.txt", SAMPLE);
let out = tally(&["--json", path.to_str().unwrap()]);
let stdout = String::from_utf8(out.stdout).unwrap();
assert_eq!(stdout.trim(), r#"{"lines":2,"words":6,"chars":24}"#);
}
#[test]
fn empty_file_fails_with_a_message() {
let path = write_temp("empty.txt", "");
let out = tally(&[path.to_str().unwrap()]);
assert!(!out.status.success());
let stderr = String::from_utf8(out.stderr).unwrap();
assert!(stderr.contains("the text is empty"), "{stderr}");
}
RSRun the tool from the workspace root. -p tally-cli picks the package; everything after -- goes to the program:
cargo run -q -p tally-cli -- sample.txt
cargo run -q -p tally-cli -- --json sample.txt
cargo run -q -p tally-cli -- missing.txt || echo "exit code $?"Check it worked
The first command prints the same two lines as the single crate did: lines=2 words=6 chars=24 and top=the (2). The second prints {"lines":2,"words":6,"chars":24}. The third prints tally: cannot read missing.txt: No such file or directory (os error 2) and then exit code 1.
Step 6 · Prove pub(crate) keeps the internals private
split_words is still in the library, and it would be tempting to call it from the CLI. Try it with a small example program in the CLI crate:
mkdir -p crates/tally-cli/examples
cat > crates/tally-cli/examples/peek.rs <<'RS'
fn main() {
let words: Vec<String> = tally_core::split_words("a b").collect();
println!("{words:?}");
}
RScargo build -p tally-cli --example peekThe build fails. That is the point: pub(crate) means public inside tally-core and invisible outside it. If the CLI really needed word splitting, the fix would be a deliberate decision to make it pub and support it as part of the library's interface. Remove the example:
rm -r crates/tally-cli/examplesCheck it worked
The build stopped with an error like error[E0603]: function 'split_words' is private, pointing at the line in peek.rs, with a note showing where the function is defined in tally-core. After the rm, ls crates/tally-cli shows only Cargo.toml, src and tests.
Step 7 · Build and test the whole workspace
From the root, --workspace selects every member:
cd ~/tally-demo
cargo build --workspace
cargo test --workspaceLook at what the workspace shares:
find . -name Cargo.lock -not -path './target/*'
find . -maxdepth 3 -name target -type d
ls target/debug/tallyThree things are worth knowing about how this behaves:
- One lock file, one build folder. All three crates resolve dependencies together into the root
Cargo.lock, so they always agree on thiserror's exact version, and each dependency is compiled once into the roottarget. On a low-end laptop that saves real disk space and build time compared with three separate projects. CommitCargo.lockfor a workspace that ships a binary. - Features are unified per build.
cargo build -p tally-corebuilds the library withoutjson.cargo build --workspacebuilds it withjson, becausetally-cliis part of the same build and asks for it. A library that compiles in the workspace can still fail when built alone, so test it alone too, as you did in the features step. - Work offline after one download.
cargo fetchdownloads every dependency the lock file names. After that,--offlinebuilds without touching the network, which helps on prepaid or metered data:
cargo fetch
cargo build --workspace --offlineCheck it worked
Every test result: line from cargo test --workspace says ok with 0 failed; you see the core unit and integration tests, the three CLI tests, and empty groups for the binary's own unit tests and the doc-tests. The first find prints only ./Cargo.lock, and the second prints only ./target: no member crate has its own. ls prints target/debug/tally, the binary from tally-cli. The offline build finishes without downloading anything.
Step 8 · Decide when a workspace is worth it, then clean up
The layout you have now grows by adding folders under crates/. A web API would be crates/tally-api depending on tally-core, with no change to the root manifest. Before you split a real project the same way, check whether it has a reason to:
- Split when a second program needs the same logic (a CLI and a server), when part of the code should be published as a library on its own, when one heavy dependency is only needed by one part, or when build times are hurting and the slow code rarely changes.
- Stay with one crate when there is only one binary and nobody else will import the logic. Modules (
mod counting;insrc/counting.rs) give you most of the tidiness with none of the extra manifests. A library and a binary can also live in one package:src/lib.rsandsrc/main.rsside by side. - Avoid crates for every folder. Each crate adds a manifest to maintain and a public interface to keep stable. Three to ten crates is common for an application; dozens usually means modules would have done.
When you have finished, remove the demo. Your Rust install stays:
cd ~
rm -rf ~/tally-demoCheck it worked
For your own project, you can name which crate each part would go in and why, or you have written down why it stays one crate. ls ~/tally-demo reports No such file or directory.
Next steps
- Give the CLI proper flags, help text and subcommands: build a command-line tool in Rust with clap.
- Design error types like
CountErrorandCliErrorwith care: handle errors in Rust with Result and the question mark operator. - Go deeper on the three kinds of tests you used here: test Rust code with unit, integration and doc tests.
Related tutorials
- Write safer PHP with strict types, enums and readonly classesYou will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
- Write reusable TypeScript with genericsYou will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
- Write regular expressions you can read and testYou will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials