4.0 The Familiar Goes to Market
No workshop produces everything it uses. Nails come from the blacksmith, glass from the glazier, every good tool from whoever makes it best. A craftsman who refuses others’ work on principle works longer and worse - and takes a separate pride in that. Cargo knows where to find what is needed.
What You Need
For tasks to survive the program stopping, they must be written to disk. But before writing
- they must be translated: a data structure in memory and bytes in a file are different things. A tool is needed that can turn one into the other and back.
In Rust this is serde - a serialization library. It is not part of the standard library:
it is a separate package on the public registry crates.io. Alongside
it, serde_json is needed - the JSON format implementation.
To Market
cargo add adds a dependency to Cargo.toml and pins the current version. For serde,
the --features derive flag is needed:
cargo add serde --features derive
cargo add serde_json
Cargo will respond roughly like this:
Updating crates.io index
Adding serde v1.0.x to dependencies
Features:
+ derive
Updating crates.io index
Adding serde_json v1.0.x to dependencies
A new section appears in Cargo.toml:
# Cargo.toml - CHANGED
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
[dependencies] is the list of everything the crate needs beyond the standard library.
version = "1" means: any backwards-compatible version from the 1.x branch. On the next
make ci run, Cargo will download the packages, compile them, and make them available to
tq’s code.
--features derive enables an optional part of serde. What exactly it provides - the
next chapter.
cargo add is convenient but not required. The same lines can be written into Cargo.toml
by hand - cargo build on the next run will notice the changes and download everything
itself.
The Result
make ci passes. On the first run Cargo will download and compile the new dependencies -
this takes a few seconds. The result is cached; the next run is faster.
The tq code has not changed - all fourteen tests are the same. What changed is the crate:
it now has dependencies, and Cargo knows where to find them.
The complete
tqcode for this chapter is in4-memory/00-the-familiar-goes-to-market/.
Lore: Cargo.lock
After the first download, Cargo creates Cargo.lock - an exact snapshot of all
dependencies: which crates, which versions, with which checksums. If Cargo.toml says “I
need version 1.x,” then Cargo.lock says “today that was 1.0.228.”
Cargo.lock should be added to git. For binary crates - always: it is the guarantee of a
reproducible build. On a different machine, on a different day, cargo build will produce
exactly the same result. Without Cargo.lock, each run may bring in a slightly different
version.
For libraries published on crates.io, Cargo.lock is usually not committed to git - so
that users of the library can choose compatible versions of dependencies themselves.