Workspace
- Rust course
- Intermediate
- Lesson 81/115
- 4 min
Manage multiple crates under one workspace.
Workspaces
A workspace groups several packages developed together under one roof. All members share one Cargo.lock and target/ folder; common dependencies are compiled once:
# root Cargo.toml
[workspace]
members = ["ortak", "api", "cli"]
[workspace.dependencies]
serde = "1"
# api/Cargo.toml
[dependencies]
ortak = { path = "../ortak" }
serde = { workspace = true }cargo build processes all members, cargo test -p api just one.
Shared code layout
A typical layout: models and helpers in the ortak library, the server and command line in separate binary packages. Each package pulls only the dependencies it needs:
proje/
├── Cargo.toml # [workspace]
├── ortak/src/lib.rs # pub fn surum()
├── api/src/main.rs # use ortak::surum;
└── cli/src/main.rs # use ortak::surum;Practice Shared version
Imitate the workspace with modules: pub fn surum() returning "1.0.0" in mod ortak, and pub fn durum() -> String using super::ortak::surum() in mod api and mod cli. Produce the output api 1.0.0 | cli 1.0.0.
Starter code
fn main() {
// buraya yaz
}Sample solution
mod ortak {
pub fn surum() -> &'static str {
"1.0.0"
}
}
mod api {
pub fn durum() -> String {
format!("api {}", super::ortak::surum())
}
}
mod cli {
pub fn durum() -> String {
format!("cli {}", super::ortak::surum())
}
}
fn main() {
println!("{} | {}", api::durum(), cli::durum());
}Expected output
api 1.0.0 | cli 1.0.0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How does one workspace member depend on another?
- With a local path dependency, path = "../ortak" Correct answer
- By downloading from crates.io
- By writing mod ortak;
- It links automatically
Explanation: A path dependency lets changes be seen immediately without publishing.
2 List the members
[workspace]
____ = ["ortak", "api", "cli"]
[workspace]
members = ["ortak", "api", "cli"]
Explanation: Workspace members are defined in the members list.
3 Item and role
| Term | Meaning |
|---|---|
[workspace] |
Workspace definition |
path = "../ortak" |
Local dependency |
workspace = true |
Use the shared version |
cargo test -p api |
Single member |