Summary - Crates and packages
- Rust course
- Intermediate
- Lesson 82/115
- 5 min
Combine a binary + library crate and a workspace to build a monorepo.
Crates and packages summary
A crate is a compilation unit: a binary (main.rs) or a library (lib.rs). A package is defined by Cargo.toml and lists dependencies; Cargo.lock locks the exact versions. Versions follow semver and "1.2" means ^1.2 by default. Features turn on optional parts (#[cfg(feature = "..")]). A workspace manages several packages with one lock file and target folder.
Parsing versions
Converting a version string to numbers and comparing as vectors gives the right order; a Vec also compares lexicographically:
fn ayristir(s: &str) -> Vec<u32> {
s.split('.').map(|p| p.parse().unwrap()).collect()
}
let a = ayristir("1.4.2"); // [1, 4, 2]
let b = ayristir("1.10.0"); // [1, 10, 0]
println!("{}", a < b); // trueReal projects use the semver crate for this; it also handles pre-release tags (1.0.0-beta) correctly.
Practice Compare versions
Write the ayristir function above. For "1.4.2" and "1.10.0", print the results of the numeric comparison (a < b) and the plain string comparison, separated by a space.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn ayristir(s: &str) -> Vec<u32> {
s.split('.').map(|p| p.parse().unwrap()).collect()
}
fn main() {
let (x, y) = ("1.4.2", "1.10.0");
println!("{} {}", ayristir(x) < ayristir(y), x < y);
}Expected output
true false
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why does the string comparison <code>"1.4.2" < "1.10.0"</code> give a wrong result?
- It gives the right result
- It doesn't compile
- It panics
- Strings compare character by character; since "4" > "1", it's false Correct answer
Explanation: Versions must be converted to numbers and compared component by component.
2 Split at dots
s.____('.').map(|p| p.parse().unwrap()).collect()
s.split('.').map(|p| p.parse().unwrap()).collect()
Explanation: split separates the version string into its components.
3 Group summary
| Term | Meaning |
|---|---|
lib.rs |
Library crate |
Cargo.lock |
Exact versions |
^1.2 |
<2.0.0 |
[workspace] |
Multiple packages |