Sub topic 4
Using the crate in your code
Earlier chapters added serde and serde_json to Cargo.toml. This chapter covers what happens next: how a dependency name in the manifest becomes a path you can write in Rust, and what goes wrong when the two disagree.
It assumes you can create a project with cargo new, read basic Rust syntax and modules, and run commands in a terminal. It also assumes you know what cargo add does.
From manifest key to crate name
Cargo and rustc cooperate here. Cargo resolves each entry in [dependencies], downloads and compiles it, and then calls rustc with one --extern name=path flag per dependency. The name in that flag is what you write in your code.
In the 2018 edition and later, every name passed with --extern is in the extern prelude. That means you can use it from any module of your package without declaring it. You do not need extern crate any more. That line only appears in old code.
Start the demo project from the earlier chapters if you do not have it:
cargo new json_demo
cd json_demo
cargo add serde --features derive
cargo add serde_jsonThen put this in src/main.rs:
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 1, y: 2 };
let json = serde_json::to_string(&p).unwrap();
println!("{json}");
let back: Point = serde_json::from_str(&json).unwrap();
println!("{back:?}");
}Running cargo run prints {"x":1,"y":2} and then Point { x: 1, y: 2 }.
Two import styles appear in this program:
use serde::{Deserialize, Serialize};brings two names into scope. After that,Serializealone is enough.serde_json::to_string(&p)uses a full path with nouse. The crate name is already visible, so the path works as written.
Both styles are correct. The usual convention is to import types and traits with use. For functions, many people keep the crate prefix (serde_json::to_string) so the reader can see where the call comes from.
How a path is resolved
The order matters for one edge case, covered in the gotchas below: a local item with the same name wins over the crate.
Package names and crate names
The name in Cargo.toml is the package name. The name in your code is the crate name. They are usually identical, with one difference: a hyphen in a package name becomes an underscore in the crate name. Identifiers in Rust cannot contain hyphens.
| In Cargo.toml | In Rust code |
|---|---|
| `serde_json = "1"` | `serde_json::...` |
| `tracing-subscriber = "0.3"` | `tracing_subscriber::...` |
| `proc-macro2 = "1"` | `proc_macro2::...` |
| `rand07 = { package = "rand", version = "0.7" }` | `rand07::...` |
The last row uses a rename. The key on the left of = is the name you get in your code, and package = "..." says which crates.io package to download. This lets one project depend on two major versions of the same crate:
[dependencies]
rand = "0.8"
rand07 = { package = "rand", version = "0.7" }fn main() {
let new: u8 = rand::random();
let old: u8 = rand07::random();
println!("{new} {old}");
}The two random functions come from different versions of the same package. Cargo compiles both and keeps them apart. Types from one version are not interchangeable with types from the other, even if they have the same name.
The crate may also declare a library name that differs from its package name. This is rare, but it exists. For example, the Cargo.toml of the ron package, or the docs of a crate, will say what the library is called. When the name you expect does not resolve, the crate's page on docs.rs shows the real path in its first example.
Macros and derive macros
Dependencies can provide macros as well as functions and types. In 2018 and later you import them like any other item:
use serde_json::json;
fn main() {
let v = json!({
"name": "Ada",
"tags": ["math", "engines"]
});
println!("{}", v["name"]);
println!("{}", v["tags"][1]);
}This prints "Ada" and "engines", with the quotes, because indexing a serde_json::Value gives another Value, and its Display implementation writes JSON text. You can skip the use and write serde_json::json!(...) instead.
Derive macros need extra care. The line #[derive(Serialize, Deserialize)] needs two separate things:
- The
SerializeandDeserializederive macros must be in scope. - The crate must have been compiled with the feature that provides them.
Serde keeps its derive macros behind the derive feature, so the features = ["derive"] in the manifest is not optional. When the feature is off, use serde::{Deserialize, Serialize}; still compiles, because it imports the traits of the same names. Only the #[derive(...)] line then fails, with an error along the lines of "cannot find derive macro Serialize in this scope". The fix is in the manifest, not in the Rust code:
cargo add serde --features deriveFeatures are covered in detail in a later chapter. For now, remember this symptom: when the Rust code looks right but a macro or item is "not found", check whether the crate documentation says it needs a feature.
Handling errors instead of unwrapping
The demo uses unwrap() to stay short. serde_json::Error implements std::error::Error, so ? works if main returns a Result:
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let p = Point { x: 1, y: 2 };
let json = serde_json::to_string(&p)?;
println!("{json}");
let back: Point = serde_json::from_str(r#"{"x": 10, "y": "oops"}"#)?;
println!("{back:?}");
Ok(())
}The second parse fails because "oops" is not an integer. The program prints the first line, then exits with a non-zero status and an error message from serde_json that includes the line and column of the problem.
Finding out what a crate offers
You rarely guess paths. Two tools show them:
- docs.rs hosts generated documentation for every published crate version. Pick the version that matches your lock file, because the API may differ between versions. Items that need a feature are labelled with the feature name.
cargo doc --openbuilds the documentation for your own package and for all of its dependencies, at the exact versions inCargo.lock, and opens it in a browser. It works offline once the crates are downloaded.
Gotchas
Only direct dependencies are visible
Your package can only use crates listed in its own manifest. Suppose serde_json depends on itoa internally. Writing use itoa::Buffer; in your code fails with an unresolved import, even though itoa is in Cargo.lock and in the build. If you need it, run cargo add itoa. Cargo then unifies versions where it can, so you do not end up compiling the crate twice without need.
The reverse case is a crate whose public API mentions types from another crate. Those types are usable without naming the crate, through method calls and inference. Naming them in a signature requires either a direct dependency or a re-export from the first crate.
Dev and build dependencies are not in `src`
A crate declared under [dev-dependencies] is only passed to rustc when compiling tests, examples and benchmarks. Using it from src/main.rs in a normal build produces an unresolved import. A crate under [build-dependencies] is only visible to build.rs. If your regular code needs the crate, move it to [dependencies].
A local item can hide a crate
Local names win over extern prelude names. This module hides the real crate within its parent module:
mod serde_json {
pub fn to_string(_: &str) -> String {
String::from("local")
}
}
fn main() {
println!("{}", serde_json::to_string("x"));
println!("{}", ::serde_json::to_string(&1).unwrap());
}The first call uses the local module and prints local. The second starts with ::, which means "look in the extern prelude only", so it reaches the crate and prints 1. This is also a useful way to be explicit in macro-generated code. Naming a module after a crate you use is better avoided.
The same crate can appear at two versions
If two dependencies need incompatible versions of a third crate, Cargo builds both. This compiles fine until you pass a type from one copy to a function that expects the other. The error says the types have the same name but are different. Use cargo tree -d (shown in a later chapter) to find duplicates, then align versions.
Checklist for a new dependency
- Add it with
cargo add, including any features the documentation requires. - Convert hyphens to underscores to get the crate name, or use the key you chose if you renamed it.
- Open the docs for the version in your lock file and copy the import path from an example.
- Run
cargo check. It compiles quickly and reports unresolved paths without producing a binary.
Exercise
A project declares tracing-subscriber = "0.3" under [dependencies]. Rust code containing use tracing-subscriber::fmt; fails to compile. What is the correct line, and why?
Show answer
use tracing_subscriber::fmt;. The package name keeps its hyphen, but the crate name is the package name with hyphens replaced by underscores, because a hyphen is not valid inside a Rust identifier.
Exercise
Your Cargo.toml has serde = "1" with no features. This code fails with "cannot find derive macro Serialize in this scope": use serde::Serialize; #[derive(Serialize)] struct P { x: i32 }. Why does the use line compile, and what is the fix?
Show answer
The use line imports the Serialize trait, which always exists. The derive macro of the same name is only provided when serde is built with the derive feature. The fix is to enable the feature, for example with cargo add serde --features derive, or by writing serde = { version = "1", features = ["derive"] } in the manifest.
Exercise
serde_json depends on itoa, so Cargo.lock lists itoa. Why does use itoa::Buffer; fail in your package, and how do you fix it?
Show answer
Only crates listed in your own manifest are passed to rustc as --extern for your package. Transitive dependencies are not in the extern prelude. Run cargo add itoa to make it a direct dependency.