Welcome to Day 26! π Today was all about managing Rust projects more efficiently and expanding what Cargo can do for us. I explored:
- Cargo Workspaces for managing multi-package projects
-
Installing binaries via
cargo install
- Extending Cargo using custom subcommands
Letβs break each of them down!
π§± Cargo Workspaces
A workspace allows you to manage multiple related packages (crates) with a shared Cargo.lock
and target
directory.
β Why Workspaces?
- Share dependencies efficiently
- Compile shared code only once
- Keep related crates organized
π§ Creating a Workspace
-
Create root folder and
Cargo.toml
without[package]
:
[workspace]
resolver = "3"
members = ["adder"]
- Create a binary crate:
cargo new adder
This auto-adds adder
to the members
list.
Your file structure now looks like:
add/
βββ Cargo.toml (workspace root)
βββ adder/
β βββ src/main.rs
βββ target/
β Adding More Crates
cargo new add_one --lib
Then update the workspace Cargo.toml
:
members = ["adder", "add_one"]
In add_one/src/lib.rs
:
pub fn add_one(x: i32) -> i32 {
x + 1
}
And in adder/Cargo.toml
:
[dependencies]
add_one = { path = "../add_one" }
π§ͺ Add a test in add_one/src/lib.rs
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
assert_eq!(add_one(2), 3);
}
}
Build and test the whole workspace from root:
cargo build
cargo test
Run a specific crate:
cargo run -p adder
cargo test -p add_one
π¦ Depending on External Crates
If you add a crate like rand
to multiple crates in the workspace, Cargo ensures they use the same version and stores a single entry in the workspace-wide Cargo.lock.
# add_one/Cargo.toml
[dependencies]
rand = "0.8.5"
use rand; // You must actually use it or get a warning
To use rand
in adder
too, add it to its Cargo.toml
. Dependencies are isolated per crate.
π¦ Publishing Crates from Workspace
Each crate needs to be published separately using -p
:
cargo publish -p add_one
π Installing Binaries with cargo install
Use this to install Rust programs published to crates.io:
cargo install ripgrep
It installs the binary to $HOME/.cargo/bin
, so make sure itβs in your $PATH
.
Run it like any other binary:
rg --help
Only crates with binary targets (i.e., have a
main.rs
) can be installed this way.
π§© Extending Cargo with Custom Commands
Cargo lets you define custom subcommands. If a binary is named cargo-something
, you can invoke it with:
cargo something
For example, after installing a custom tool with cargo install
, you can run it as if it were built-in:
cargo expand
Check all installed commands:
cargo --list
This extensibility makes Cargo incredibly flexible!
π§ Summary
- Workspaces simplify multi-crate projects
-
cargo install
gives you access to tools likeripgrep
,cargo-edit
, etc. - Custom commands help extend your workflow
π Stay tuned as I continue my #100DaysOfRust journey. Follow me @SubeshDev for updates, and check out the full post on dev.to!
Top comments (0)