Sub topic 2
Using a Rust Crate in Your Code
Assume Rust and Cargo are installed, and that you can create a project, edit Rust modules, and run terminal commands. This chapter uses serde for serialization and serde_json for JSON.
Use the crate in your code
Add the crates to Cargo.toml:
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"The serde crate provides serialization traits. The derive feature lets Rust generate implementations from attributes. serde_json converts values to and from JSON.
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let point = Point { x: 1, y: 2 };
let text = serde_json::to_string(&point).unwrap();
println!("{text}");
let decoded: Point = serde_json::from_str(&text).unwrap();
println!("{decoded:?}");
}Cargo makes the dependency available to the package. Rust code imports its public items with use.
Version requirements and SemVer compatibility
Semantic Versioning, or SemVer, uses major.minor.patch numbers. Cargo usually interprets a plain version as a caret requirement:
| Requirement | Typical allowed range |
|---|---|
| `1.2.3` | `>=1.2.3, <2.0.0` |
| `~1.2.3` | `>=1.2.3, <1.3.0` |
| `=1.2.3` | Exactly `1.2.3` |
For versions below 1.0.0, Cargo uses the first non-zero component as the compatibility boundary. Thus 0.2.3 normally allows versions below 0.3.0, while 0.0.3 allows versions below 0.0.4.
Cargo.lock and reproducible builds
Cargo.lock records the exact versions and checksums Cargo selected, including transitive dependencies. A later build can therefore reproduce the same dependency graph even when newer compatible releases exist.
For an application or binary, commit Cargo.lock to version control. For a library, committing it is optional, because downstream applications resolve the library's dependencies themselves.
Enabling and disabling features
Features are optional crate capabilities. They can add APIs or dependencies. Disable defaults when you need a smaller or more controlled dependency:
[dependencies]
tokio = { version = "1", default-features = false, features = ["rt", "macros"] }Check a crate's documentation before selecting features. Features can affect compile time, supported platforms, and available APIs.
Exercise
What does features = ["derive"] enable for serde?
Show answer
It enables generated implementations such as Serialize and Deserialize for structs with derive attributes.