Sub topic 4
Using the crate in your code
This chapter assumes you can create a project with cargo new, you know basic Rust syntax and modules, and you have already added serde and serde_json to a project with cargo add. Here you will see how a dependency's name becomes a path in your code, and how to fix the errors that appear when that connection breaks.
From package name to crate name
Cargo downloads and compiles every dependency listed in [dependencies]. It then passes each one to rustc with an --extern flag. Because of that flag, the crate name is already in scope in every module of your project. You do not write extern crate (required only in the 2015 edition) and you do not declare a mod for it.
The name in your code comes from the key in Cargo.toml, with one rule: hyphens become underscores. A package called serde-json on crates.io is used as serde_json. Hyphens are not valid in Rust identifiers.
| Key in Cargo.toml | Path in Rust code |
|---|---|
| `serde` | `serde::...` |
| `serde_json` | `serde_json::...` |
| `rand07 = { package = "rand", ... }` | `rand07::...` |
The last row comes from a renamed dependency, covered in a later chapter. The key you wrote is the name you use, not the name on crates.io.
A complete example
Start with the project from the previous chapter. Its manifest has these dependencies:
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"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:?}");
}Run it with cargo run. The output is:
{"x":1,"y":2}
Point { x: 1, y: 2 }The program uses the dependencies in two ways:
use serde::{Deserialize, Serialize};imports the two traits. It also imports the derive macros of the same names, which is why thederivefeature must be on.serde_json::to_stringis called by its full path. Nouseis needed for that.
Two ways to refer to items
You can write the full path each time, or bring the item into scope with use. Both are equivalent. The usual convention is to import types and traits, and to call functions through their parent module so the origin stays visible.
use serde_json::Value;
fn main() {
let v: Value = serde_json::from_str(r#"{"name":"Ferris"}"#).unwrap();
println!("{}", v["name"]);
}Here Value is imported because it is a type used in a signature. from_str stays qualified, so a reader can tell it comes from serde_json.
Inside a module
Paths that start with a crate name work from any module, including nested ones. A path that starts with crate:: refers to your own crate, so the two never collide in normal use.
mod report {
pub fn render(value: &serde_json::Value) -> String {
serde_json::to_string_pretty(value).unwrap()
}
}If you create a local module with the same name as a dependency, the local item can shadow it in some contexts. In that case, write ::serde_json::... with a leading :: to name the external crate explicitly.
Common errors
Other frequent failures:
cannot find derive macro Serialize: thederivefeature is not enabled. Runcargo add serde --features derive.unresolved importfor a dependency listed only under[dev-dependencies]: dev-dependencies are visible to tests, examples and benchmarks, but not tosrc/main.rsin a normal build.- Type annotations needed:
serde_json::from_stris generic over its return type. Writelet back: Point = ...or use the turbofish,from_str::<Point>(&json). - Two versions of one crate: a type from
foo 1.xis not the same type as one fromfoo 2.x. The compiler message names both versions. Section "Inspecting the dependency tree" shows how to find the cause.
Reading the documentation
Each crate has generated API documentation on docs.rs. You can also build the documentation for your exact dependency versions locally with cargo doc --open. This shows the versions in Cargo.lock, not the latest release, which avoids reading docs for an API you do not have.
Exercise
A manifest contains serde-json = "1". How do you call its to_string function in code, and why does cargo run fail with "cannot find derive macro Serialize" even though serde is listed?
Show answer
Call it as serde_json::to_string(...), because hyphens in the key become underscores. The derive macro error means serde's derive feature is not enabled, so the fix is cargo add serde --features derive.