Workspaces

When the code base is getting larger, you might need to work on multiple crates on the same project. Rust supports this via Workspaces. You can build, run tests or generate docs for all crates at once by running cargo commands from the project root.

⭐️ When working on multiple crates same time, there is a higher possibility to having shared dependencies on crates. To prevent downloading and compiling the same dependency multiple times, Rust uses a shared build directory under the project root, while running cargo build from the project root.

// # Think we run
mkdir greetings
touch greetings/Cargo.toml
cargo new greetings/lib
cargo new --bin greetings/examples/hello

// # That generates,
.
├── Cargo.toml
├── examples
│  └── hello
│     ├── Cargo.toml
│     └── src
│        └── main.rs
└── lib
   ├── Cargo.toml
   └── src
      └── lib.rs

// # Think we modify following files

// 01. greetings/Cargo.toml
[workspace]
members = [
    "lib",
    "examples/hello"
]

// 02.1 greetings/lib/Cargo.toml
[package]
name = "greetings"
version = "0.1.0"
authors = ["Dumindu Madunuwan"]

[dependencies]

// 02.2 greetings/lib/src/lib.rs
pub fn hello() {
    println!("Hello, world!");
}

// 03.1 greetings/examples/hello/Cargo.toml
[package]
name = "hello"
version = "0.1.0"
authors = ["Dumindu Madunuwan"]

[dependencies]
greetings = { path = "../../lib" }

// 03.2 greetings/examples/hello/src/main.rs
extern crate greetings;

fn main() {
    greetings::hello();
}

🔎 rust-lang/rust source folder is a good example for a workspace.

Last updated