- Mastering Rust
- Rahul Sharma Vesa Kaihlavirta
- 385字
- 2021-07-02 13:35:21
Cargo workspace
Over the course of time, your project has gotten quite large. Now, you are thinking about whether you could split the common parts of your code as separate crates to help manage complexity. Well, a Cargo workspace allows you to do just that. The concept of workspaces is that they allow you to have crates locally in a directory that can share the same Cargo.lock file and a common target or output directory. To demonstrate this, we'll create a new project that incorporates Cargo workspaces. The workspace is nothing but a directory with a Cargo.toml file in it. It doesn't have any [package] section, but has a [workspace] section in it. Let's create a new directory called workspace_demo and add the Cargo.toml file like so:
mkdir workspace_demo
cd workspace_demo && touch Cargo.toml
We then add the workspace section to our Cargo.toml file:
# worspace_demo/Cargo.toml
[workspace]
members = ["my_crate", "app"]
Within [workspace], the members key is a list of crates within the workspace directory. Now, within the workspace_demo directory, we'll create two crates: my_crate, a library crate and app, a binary crate that uses my_crate.
To keep things simple, my_crate has a public API that simply prints a greeting message:
// workspace_demo/my_crate/lib.rs
pub fn greet() {
println!("Hi from my_crate");
}
Now, from our app crate, we have the main function, which calls the greet function of my_crate:
// workspace_demo/app/main.rs
fn main() {
my_crate::greet();
}
However, we need to let Cargo know about our my_crate dependency. As my_crate is a local crate, we need to specify it as a path dependency in the Cargo.toml file of app, like so:
# workspace_demo/app/Cargo.toml
[package]
name = "app"
version = "0.1.0"
authors = ["creativcoder"]
edition = "2018"
[dependencies]
my_crate = { path = "../my_crate" }
Now, when we run cargo build, the binary gets generated in the workspace_demo directory's target directory. Accordingly, we can add multiple local crates within the workspace_demo directory. Now, if we want to add a third-party dependency from crates.io, we need to add it in all of the crates where we need it. However, during cargo build, Cargo makes sure to only have a single version for that dependency in the Cargo.lock file. This ensures that third-party dependencies do not get rebuilt and duplicated.
- Java 開發(fā)從入門到精通(第2版)
- LabVIEW程序設計基礎與應用
- C# 2012程序設計實踐教程 (清華電腦學堂)
- Windows系統(tǒng)管理與服務配置
- Mastering Natural Language Processing with Python
- Production Ready OpenStack:Recipes for Successful Environments
- Blender 3D Incredible Machines
- PLC編程及應用實戰(zhàn)
- C++反匯編與逆向分析技術揭秘(第2版)
- Java程序設計教程
- Python Social Media Analytics
- C語言程序設計教程
- Java Web動態(tài)網(wǎng)站開發(fā)(第2版·微課版)
- Java程序設計及應用開發(fā)
- Spring Boot學習指南:構建云原生Java和Kotlin應用程序