Chapter 14
More About Cargo and Crates.io
So far we’ve used only the most basic features of Cargo to build, run, and test our code, but it can do a lot more. This chapter discusses some of its other, more advanced features, to show you how to:
- customize your build through release profiles (14.1);
- publish libraries on crates.io (14.2);
- organize large projects with workspaces (14.3);
- install binaries from crates.io (14.4);
- extend Cargo using custom commands (14.5).
Cargo can do even more than this chapter covers; for a full explanation of all its features, see its documentation (doc.rust-lang.org/cargo).
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
1
Chapter 14 · 14.1 Customizing Builds with Release Profiles
Release profiles: dev and release
Definition 14.1 (Release profile). One of Rust’s predefined, customizable profiles with different configurations that give a programmer more control over various options for compiling code. Each profile is configured independently of the others.
Cargo has two main profiles:
- the dev profile, which Cargo uses when you run cargo build — defined with good defaults for development;
- the release profile, which Cargo uses when you run cargo build --release — with good defaults for release builds.
These profile names might be familiar from the output of your builds:
$ cargo build
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s
$ cargo build --release
Finished `release` profile [optimized] target(s) in 0.32s
The dev and release shown here are these different profiles used by the compiler.
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
2
Chapter 14 · 14.1 Customizing Builds with Release Profiles
Default settings and the opt-level setting
Cargo has default settings for each profile that apply when you haven’t explicitly added any [profile.*] sections to the project’s Cargo.toml. By adding [profile.*] sections for any profile you want to customize, you override any subset of the default settings. For example, these are the defaults for opt-level:
Cargo.toml
[profile.dev]
opt-level = 0
[profile.release]
opt-level = 3
Definition 14.2 (opt-level). The profile setting that controls the number of optimizations Rust will apply to your code, in a range of 0 to 3.
- Applying more optimizations extends compiling time.
- In development you compile often, so you want fewer optimizations to compile faster, even if the resulting code runs slower: the default opt-level for dev is 0.
- For release it’s best to spend more time compiling: you compile in release mode once but run the program many times, so release mode trades longer compile time for faster code — the default for release is 3.
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
3
Chapter 14 · 14.1 Customizing Builds with Release Profiles
Overriding a default setting
You override a default by adding a different value for it in Cargo.toml. For example, to use optimization level 1 in the development profile, add these two lines to the project’s Cargo.toml:
Cargo.toml
[profile.dev]
opt-level = 1
- This overrides the default setting of 0.
- Now cargo build uses the defaults for the dev profile plus our customization to opt-level.
- Because opt-level is 1, Cargo applies more optimizations than the default, but not as many as in a release build.
Remark. For the full list of configuration options and defaults for each profile, see Cargo’s documentation (doc.rust-lang.org/cargo/reference/profiles.html).
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
4
Chapter 14 · 14.2 Publishing a Crate to Crates.io
Sharing code, and documentation comments
We’ve used packages from crates.io as dependencies of our projects, but you can also share your code with other people by publishing your own packages. The crate registry at crates.io distributes the source code of your packages, so it primarily hosts code that is open source.
Rust and Cargo have features that make your published package easier for people to find and use. We look at some of them first, and then at how to publish a package.
Making useful documentation comments
Accurately documenting your packages helps other users know how and when to use them, so it’s worth investing the time to write documentation. Chapter 3 showed ordinary comments with two slashes, //. Rust also has a particular kind of comment for documentation:
Definition 14.3 (Documentation comment). A comment written with three slashes, ///, instead of two, that supports Markdown notation for formatting the text and is placed just before the item it documents. It generates HTML documentation, which displays the documentation comments of public API items for programmers interested in knowing how to use your crate as opposed to how your crate is implemented.
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
5
Chapter 14 · 14.2 Publishing a Crate to Crates.io
Documenting add_one, and generating the docs
Listing 14.1 shows documentation comments for an add_one function in a crate named my_crate.
Listing 14.1: A documentation comment for a function — src/lib.rs
/// Adds one to the number given.
///
/// # Examples
///
/// ```
/// let arg = 5;
/// let answer = my_crate::add_one(arg);
///
/// assert_eq!(6, answer);
/// ```
pub fn add_one(x: i32) -> i32 {
x + 1
}
We describe what add_one does, start a section with the heading Examples, and then provide code that demonstrates how to use add_one.
cargo doc generates the HTML documentation from this comment: it runs the rustdoc tool distributed with Rust and puts the HTML in the target/doc directory.
For convenience, cargo doc --open builds the HTML for your crate (and for all of its dependencies) and opens it in a web browser. Navigate to add_one to see the rendered text (the book’s Figure 14-1).
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
6
Chapter 14 · 14.2 Publishing a Crate to Crates.io
Commonly used documentation sections
The # Examples Markdown heading in Listing 14.1 creates a section in the HTML titled “Examples.” Crate authors commonly use these other sections too:
Table 14.1: Common sections of a documentation comment
| Section | What it describes |
|---|---|
| Panics | The scenarios in which the documented function could panic. Callers who don’t want their programs to panic should make sure they don’t call the function in these situations. |
| Errors | If the function returns a Result: the kinds of errors that might occur and the conditions that cause them, so callers can write code to handle different kinds of errors in different ways. |
| Safety | If the function is unsafe to call (unsafety: Chapter 20): why it is unsafe, and the invariants the function expects callers to uphold. |
Most documentation comments don’t need all of these sections, but this is a good checklist of the aspects of your code users will be interested in knowing about.
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
7
Chapter 14 · 14.2 Publishing a Crate to Crates.io
Documentation comments as tests
Example code blocks in your documentation comments demonstrate how to use your library — with an additional bonus: running cargo test runs the code examples in your documentation as tests!
Nothing is better than documentation with examples. But nothing is worse than examples that don’t work because the code has changed since the documentation was written. Running cargo test with the documentation of add_one from Listing 14.1 shows a section like this in the test results:
Doc-tests my_crate
running 1 test
test src/lib.rs - add_one (line 5) ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.27s
Now, if we change either the function or the example so that the assert_eq! in the example panics, and run cargo test again, the doc tests catch that the example and the code are out of sync with each other!
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
8
Chapter 14 · 14.2 Publishing a Crate to Crates.io
Contained item comments: //!
Definition 14.4 (Contained item comment). A doc comment written //!. It adds documentation to the item that contains the comments rather than to the items following the comments. It is typically used inside the crate root file (src/lib.rs by convention) or inside a module, to document the crate or the module as a whole.
For example, to describe the purpose of the my_crate crate that contains the add_one function, we add documentation comments that start with //! to the beginning of the src/lib.rs file, as in Listing 14.2.
Listing 14.2: The documentation for the my_crate crate as a whole — src/lib.rs
//! # My Crate
//!
//! `my_crate` is a collection of utilities to make performing certain
//! calculations more convenient.
/// Adds one to the number given.
// --snip--
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
9
Chapter 14 · 14.2 Publishing a Crate to Crates.io
Documenting the crate as a whole
Notice there isn’t any code after the last line that begins with //!. Because these comments start with //! instead of ///, they document the item that contains them rather than an item that follows them. Here that item is the src/lib.rs file, the crate root: these comments describe the entire crate.
Table 14.2: The two kinds of documentation comment
| Comment | Documents |
|---|---|
| /// | the item that follows the comment (a function, struct, enum, …) |
| //! | the item that contains the comment (the crate root file, or a module) |
When we run cargo doc --open, these comments display on the front page of the documentation for my_crate, above the list of public items in the crate (the book’s Figure 14-2: the rendered documentation for my_crate, including the comment describing the crate as a whole).
Remark. Documentation comments within items are useful for describing crates and modules especially. Use them to explain the overall purpose of the container, to help your users understand the crate’s organization.
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
10
Chapter 14 · 14.2 Publishing a Crate to Crates.io
Exporting a convenient public API
The structure of your public API is a major consideration when publishing a crate. People who use your crate are less familiar with the structure than you are, and might have difficulty finding the pieces they want to use if your crate has a large module hierarchy.
Chapter 7 covered making items public with the pub keyword and bringing items into a scope with use. But the structure that makes sense to you while developing a crate might not be convenient for your users. If you organize your structs in a hierarchy of multiple levels, people who want a type defined deep in it might have trouble finding out that the type exists. They might also be annoyed at having to enter use my_crate::some_module::another_module::UsefulType; rather than use my_crate::UsefulType;.
The good news: if the structure isn’t convenient for others to use from another library, you don’t have to rearrange your internal organization. Instead, you can re-export items with pub use to make a public structure that’s different from your private structure.
Definition 14.5 (Re-exporting). Taking a public item in one location and making it public in another location, as if it were defined in the other location instead.
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
11
Chapter 14 · 14.2 Publishing a Crate to Crates.io
An art library organized into modules
For example, say we made a library named art for modeling artistic concepts. It has two modules: a kinds module containing two enums named PrimaryColor and SecondaryColor, and a utils module containing a function named mix.
Listing 14.3: An art library with items organized into kinds and utils modules — src/lib.rs
//! # Art
//!
//! A library for modeling artistic concepts.
pub mod kinds {
/// The primary colors according to the RYB color model.
pub enum PrimaryColor {
Red,
Yellow,
Blue,
}
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
12
Chapter 14 · 14.2 Publishing a Crate to Crates.io
The art library: SecondaryColor and utils
Listing 14.3 (continued): the rest of the kinds module, and the utils module — src/lib.rs
/// The secondary colors according to the RYB color model.
pub enum SecondaryColor {
Orange,
Green,
Purple,
}
}
pub mod utils {
use crate::kinds::*;
/// Combines two primary colors in equal amounts to create
/// a secondary color.
pub fn mix(c1: PrimaryColor, c2: PrimaryColor) -> SecondaryColor {
// --snip--
}
}
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
13
Chapter 14 · 14.2 Publishing a Crate to Crates.io
Using art through its internal structure
The front page of the documentation that cargo doc generates for this crate (the book’s Figure 14-3) lists only the kinds and utils modules. The PrimaryColor and SecondaryColor types aren’t listed on the front page, nor is the mix function: we have to click kinds and utils to see them.
Another crate that depends on this library needs use statements that bring the items from art into scope, specifying the module structure that’s currently defined. Listing 14.4 uses the PrimaryColor and mix items:
Listing 14.4: A crate using the art crate’s items with its internal structure exported — src/main.rs
use art::kinds::PrimaryColor;
use art::utils::mix;
fn main() {
let red = PrimaryColor::Red;
let yellow = PrimaryColor::Yellow;
mix(red, yellow);
}
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
14
Chapter 14 · 14.2 Publishing a Crate to Crates.io
Why the internal structure hurts users
The author of the code in Listing 14.4 had to figure out that PrimaryColor is in the kinds module and mix is in the utils module.
- The module structure of the art crate is more relevant to developers working on the crate than to those using it.
- The internal structure contains no useful information for someone trying to understand how to use art; rather, it causes confusion.
- Developers who use the crate have to figure out where to look, and must specify the module names in their use statements.
To remove the internal organization from the public API, we can modify the art crate code of Listing 14.3 to add pub use statements that re-export the items at the top level, as shown in Listing 14.5 on the next slide.
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
15
Chapter 14 · 14.2 Publishing a Crate to Crates.io
Re-exporting items with pub use
Listing 14.5: Adding pub use statements to re-export items — src/lib.rs
//! # Art
//!
//! A library for modeling artistic concepts.
pub use self::kinds::PrimaryColor;
pub use self::kinds::SecondaryColor;
pub use self::utils::mix;
pub mod kinds {
// --snip--
}
pub mod utils {
// --snip--
}
The three pub use lines re-export the items at the top level; the modules stay as they were.
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
16
Chapter 14 · 14.2 Publishing a Crate to Crates.io
Using the re-exported items
The API documentation that cargo doc generates for this crate now lists and links the re-exports on the front page (the book’s Figure 14-4), making the PrimaryColor and SecondaryColor types and the mix function easier to find.
Users of the art crate can still see and use the internal structure from Listing 14.3, as demonstrated in Listing 14.4, or they can use the more convenient structure of Listing 14.5, as in Listing 14.6:
Listing 14.6: A program using the re-exported items from the art crate — src/main.rs
use art::PrimaryColor;
use art::mix;
fn main() {
// --snip--
let red = PrimaryColor::Red;
let yellow = PrimaryColor::Yellow;
mix(red, yellow);
}
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
17
Chapter 14 · 14.2 Publishing a Crate to Crates.io
When and why to use pub use
- Where there are many nested modules, re-exporting the types at the top level with pub use can make a significant difference in the experience of people who use the crate.
- Another common use of pub use is to re-export definitions of a dependency in the current crate, to make that crate’s definitions part of your crate’s public API.
Creating a useful public API structure is more an art than a science, and you can iterate to find the API that works best for your users. Choosing pub use gives you flexibility in how you structure your crate internally, and decouples that internal structure from what you present to your users.
Remark. Look at some of the code of crates you’ve installed to see whether their internal structure differs from their public API.
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
18
Chapter 14 · 14.2 Publishing a Crate to Crates.io
Setting up a crates.io account
Before you can publish any crates, you need an account on crates.io and an API token:
- Visit the home page at crates.io and log in via a GitHub account. (A GitHub account is currently a requirement, but the site might support other ways of creating an account in the future.)
- Once logged in, visit your account settings at crates.io/me/ and retrieve your API key.
- Run the cargo login command and paste your API key when prompted:
$ cargo login
abcdefghijklmnopqrstuvwxyz012345
This informs Cargo of your API token and stores it locally in ~/.cargo/credentials.toml.
Remark. This token is a secret: do not share it with anyone else. If you do share it with anyone for any reason, revoke it and generate a new token on crates.io.
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
19
Chapter 14 · 14.2 Publishing a Crate to Crates.io
Adding metadata: a unique crate name
Say you have a crate you want to publish. Before publishing, you need to add some metadata in the [package] section of the crate’s Cargo.toml file. First, your crate needs a unique name:
- While working on a crate locally, you can name it whatever you like.
- Crate names on crates.io, however, are allocated on a first-come, first-served basis: once a name is taken, no one else can publish a crate with that name.
- Before attempting to publish, search for the name you want to use. If it has been used, find another name and edit the name field under [package] to use the new name for publishing:
Cargo.toml
[package]
name = "guessing_game"
Even with a unique name, running cargo publish at this point gives you a warning and then an error (next slide).
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
20
Chapter 14 · 14.2 Publishing a Crate to Crates.io
Publishing without a description or license fails
$ cargo publish
Updating crates.io index
warning: manifest has no description, license, license-file, documentation, homepage or repository.
See https://doc.rust-lang.org/cargo/reference/manifest.html#package-metadata for more info.
--snip--
error: failed to publish to registry at https://crates.io
Caused by:
the remote server responded with an error (status 400 Bad Request): missing or empty metadata
fields: description, license. Please see https://doc.rust-lang.org/cargo/reference/manifest.html
for more information on configuring these fields
This results in an error because you’re missing some crucial information: a description and a license are required, so that people will know what your crate does and under what terms they can use it.
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
21
Chapter 14 · 14.2 Publishing a Crate to Crates.io
Adding a description and a license
- description: just a sentence or two, because it appears with your crate in search results.
- license: you need to give a license identifier value.
Definition 14.6 (License identifier value). A standard identifier naming a license; the Linux Foundation’s Software Package Data Exchange (SPDX, spdx.org/licenses) lists the identifiers you can use.
For example, to specify that you’ve licensed your crate using the MIT License, add the MIT identifier:
Cargo.toml
[package]
name = "guessing_game"
license = "MIT"
To use a license that doesn’t appear in the SPDX, place the text of that license in a file, include the file in your project, and then use license-file to specify the name of that file instead of using the license key.
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
22
Chapter 14 · 14.2 Publishing a Crate to Crates.io
Dual licensing, and a manifest ready to publish
Which license suits your project is beyond the scope of the book. Many Rust projects are licensed like Rust itself, with the dual license MIT OR Apache-2.0: multiple identifiers separated by OR give your project multiple licenses.
With a unique name, the version, a description, and a license, a manifest ready to publish might look like this:
Cargo.toml
[package]
name = "guessing_game"
version = "0.1.0"
edition = "2024"
description = "A fun game where you guess what number the computer has chosen."
license = "MIT OR Apache-2.0"
[dependencies]
Remark. Cargo’s documentation (doc.rust-lang.org/cargo) describes other metadata you can specify so others can discover and use your crate more easily.
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
23
Chapter 14 · 14.2 Publishing a Crate to Crates.io
Publishing to crates.io is permanent
Now that you’ve created an account, saved your API token, chosen a name for your crate, and specified the required metadata, you’re ready to publish! Publishing a crate uploads a specific version to crates.io for others to use.
Be careful: a publish is permanent
- The version can never be overwritten, and the code cannot be deleted except in certain circumstances.
- One major goal of crates.io is to act as a permanent archive of code, so that builds of all projects that depend on crates from crates.io will continue to work. Allowing version deletions would make fulfilling that goal impossible.
- However, there is no limit to the number of crate versions you can publish.
Run the cargo publish command again. It should succeed now (output on the next slide).
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
24
Chapter 14 · 14.2 Publishing a Crate to Crates.io
A successful cargo publish
$ cargo publish
Updating crates.io index
Packaging guessing_game v0.1.0 (file:///projects/guessing_game)
Packaged 6 files, 1.2KiB (895.0B compressed)
Verifying guessing_game v0.1.0 (file:///projects/guessing_game)
Compiling guessing_game v0.1.0
(file:///projects/guessing_game/target/package/guessing_game-0.1.0)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.19s
Uploading guessing_game v0.1.0 (file:///projects/guessing_game)
Uploaded guessing_game v0.1.0 to registry `crates-io`
note: waiting for `guessing_game v0.1.0` to be available at registry
`crates-io`.
You may press ctrl-c to skip waiting; the crate should be available shortly.
Published guessing_game v0.1.0 at registry `crates-io`
Congratulations! You’ve now shared your code with the Rust community, and anyone can easily add your crate as a dependency of their project.
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
25
Chapter 14 · 14.2 Publishing a Crate to Crates.io
New versions, and deprecating old ones
Publishing a new version of an existing crate
When you’ve made changes to your crate and are ready to release a new version, change the version value in your Cargo.toml and republish. Use the Semantic Versioning rules (semver.org) to decide on an appropriate next version number, based on the kinds of changes you’ve made. Then run cargo publish to upload the new version.
Deprecating versions from crates.io
Although you can’t remove previous versions of a crate, you can prevent any future projects from adding them as a new dependency. This is useful when a crate version is broken for one reason or another. For such situations, Cargo supports yanking a crate version.
Definition 14.7 (Yanking). Preventing new projects from depending on a published crate version while allowing all existing projects that depend on it to continue. Essentially, all projects with a Cargo.lock will not break, and any future Cargo.lock files generated will not use the yanked version.
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
26
Chapter 14 · 14.2 Publishing a Crate to Crates.io
Yanking and unyanking with cargo yank
To yank a version, run cargo yank in the directory of the crate you previously published, and specify which version to yank. For example, having published guessing_game version 1.0.1, we’d run this in the project directory for guessing_game:
$ cargo yank --vers 1.0.1
Updating crates.io index
Yank guessing_game@1.0.1
Adding --undo to the command undoes a yank and allows projects to start depending on that version again:
$ cargo yank --vers 1.0.1 --undo
Updating crates.io index
Unyank guessing_game@1.0.1
Remark. A yank does not delete any code. It cannot, for example, delete accidentally uploaded secrets. If that happens, you must reset those secrets immediately.
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
27
Chapter 14 · 14.3 Cargo Workspaces
Workspaces: several packages developed together
In Chapter 12 we built a package that included a binary crate and a library crate. As your project develops, the library crate might keep getting bigger, and you may want to split your package further into multiple library crates. Cargo’s workspaces help manage multiple related packages that are developed in tandem.
Definition 14.8 (Workspace). A set of packages that share the same Cargo.lock and output directory.
Creating a workspace
The example uses trivial code, to concentrate on the structure. There are multiple ways to structure a workspace; this is one common way: a workspace containing a binary and two libraries. The binary provides the main functionality and depends on the two libraries; one library provides an add_one function, the other an add_two function. Start with a new directory for the workspace:
$ mkdir add
$ cd add
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
28
Chapter 14 · 14.3 Cargo Workspaces
The workspace manifest, and the first member
In the add directory, create the Cargo.toml file that configures the entire workspace. It has no [package] section; instead it starts with a [workspace] section that lets us add members to the workspace. We also use the latest and greatest version of Cargo’s resolver algorithm by setting resolver to "3":
Cargo.toml
[workspace]
resolver = "3"
Next, create the adder binary crate by running cargo new within the add directory:
$ cargo new adder
Created binary (application) `adder` package
Adding `adder` as member of workspace at `file:///projects/add`
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
29
Chapter 14 · 14.3 Cargo Workspaces
The members key, and the workspace layout
Running cargo new inside a workspace also automatically adds the newly created package to the members key in the [workspace] definition of the workspace Cargo.toml:
Cargo.toml
[workspace]
resolver = "3"
members = ["adder"]
At this point we can build the workspace by running cargo build. The files in the add directory should look like this:
├── Cargo.lock
├── Cargo.toml
├── adder
│ ├── Cargo.toml
│ └── src
│ └── main.rs
└── target
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
30
Chapter 14 · 14.3 Cargo Workspaces
One shared target directory
- The workspace has one target directory at the top level, into which the compiled artifacts are placed; the adder package doesn’t have its own target directory.
- Even if we run cargo build from inside the adder directory, the compiled artifacts still end up in add/target rather than add/adder/target.
Why Cargo structures it this way
The crates in a workspace are meant to depend on each other. If each crate had its own target directory, each crate would have to recompile each of the other crates in the workspace to place the artifacts in its own target directory. By sharing one target directory, the crates avoid unnecessary rebuilding.
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
31
Chapter 14 · 14.3 Cargo Workspaces
Creating the second package in the workspace
Next, create another member package in the workspace, called add_one. Generate a new library crate named add_one:
$ cargo new add_one --lib
Created library `add_one` package
Adding `add_one` as member of workspace at `file:///projects/add`
The top-level Cargo.toml now includes the add_one path in the members list:
Cargo.toml
[workspace]
resolver = "3"
members = ["adder", "add_one"]
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
32
Chapter 14 · 14.3 Cargo Workspaces
Two members, and the add_one function
The add directory should now have these directories and files:
├── Cargo.lock
├── Cargo.toml
├── add_one
│ ├── Cargo.toml
│ └── src
│ └── lib.rs
├── adder
│ ├── Cargo.toml
│ └── src
│ └── main.rs
└── target
In the add_one/src/lib.rs file, add an add_one function:
add_one/src/lib.rs
pub fn add_one(x: i32) -> i32 {
x + 1
}
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
33
Chapter 14 · 14.3 Cargo Workspaces
A path dependency between members
To have the adder package (our binary) depend on the add_one package (our library), first add a path dependency on add_one to adder/Cargo.toml:
adder/Cargo.toml
[dependencies]
add_one = { path = "../add_one" }
Cargo doesn’t assume that crates in a workspace will depend on each other, so we need to be explicit about the dependency relationships.
Next, use the add_one function (from the add_one crate) in the adder crate: change main in adder/src/main.rs to call it, as in Listing 14.7.
Listing 14.7: Using the add_one library crate from the adder crate — adder/src/main.rs
fn main() {
let num = 10;
println!("Hello, world! {num} plus one is {}!", add_one::add_one(num));
}
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
34
Chapter 14 · 14.3 Cargo Workspaces
Building the workspace, and running one package
Build the workspace by running cargo build in the top-level add directory:
$ cargo build
Compiling add_one v0.1.0 (file:///projects/add/add_one)
Compiling adder v0.1.0 (file:///projects/add/adder)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.22s
To run the binary crate from the add directory, specify which package in the workspace to run with the -p argument and the package name with cargo run:
$ cargo run -p adder
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s
Running `target/debug/adder`
Hello, world! 10 plus one is 11!
This runs the code in adder/src/main.rs, which depends on the add_one crate.
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
35
Chapter 14 · 14.3 Cargo Workspaces
Depending on an external package
The workspace has only one Cargo.lock file, at the top level, rather than one in each crate’s directory, so all crates use the same version of all dependencies. If we add the rand package to both adder/Cargo.toml and add_one/Cargo.toml, Cargo resolves both to one version of rand and records that in the one Cargo.lock. Using the same dependencies means the crates in the workspace will always be compatible with each other.
Add the rand crate to the [dependencies] section of add_one/Cargo.toml, so that the add_one crate can use it:
add_one/Cargo.toml
[dependencies]
rand = "0.10.1"
Now add use rand; to add_one/src/lib.rs. Running cargo build in the add directory brings in and compiles the rand crate, with one warning because we don’t refer to the rand we brought into scope (next slide).
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
36
Chapter 14 · 14.3 Cargo Workspaces
Building with rand: an unused-import warning
$ cargo build
Updating crates.io index
Downloaded rand v0.10.1
--snip--
Compiling rand v0.10.1
Compiling add_one v0.1.0 (file:///projects/add/add_one)
warning: unused import: `rand`
--> add_one/src/lib.rs:1:5
|
1 | use rand;
| ^^^^
|
= note: `#[warn(unused_imports)]` (part of `#[warn(unused)]`) on by default
warning: `add_one` (lib) generated 1 warning (run `cargo fix --lib -p add_one` to apply 1 suggestion)
Compiling adder v0.1.0 (file:///projects/add/adder)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.95s
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
37
Chapter 14 · 14.3 Cargo Workspaces
Each crate must declare its own dependencies
The top-level Cargo.lock now records that add_one depends on rand. But other crates in the workspace can’t use rand unless we add it to their Cargo.toml files as well. Adding use rand; to adder/src/main.rs gives an error:
$ cargo build
--snip--
Compiling adder v0.1.0 (file:///projects/add/adder)
error[E0432]: unresolved import `rand`
--> adder/src/main.rs:2:5
|
2 | use rand;
| ^^^^ no external crate `rand`
To fix this, list rand as a dependency in the adder package’s Cargo.toml too. Building adder then adds rand to its dependencies in Cargo.lock, but no additional copies are downloaded: every crate in the workspace using rand uses the same version, as long as they specify compatible versions — saving space and keeping the crates compatible.
Remark. If crates in the workspace specify incompatible versions of the same dependency, Cargo resolves each of them, but still tries to resolve as few versions as possible.
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
38
Chapter 14 · 14.3 Cargo Workspaces
Adding a test to a workspace
For another enhancement, add a test of the add_one::add_one function within the add_one crate:
add_one/src/lib.rs
pub fn add_one(x: i32) -> i32 {
x + 1
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
assert_eq!(3, add_one(2));
}
}
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
39
Chapter 14 · 14.3 Cargo Workspaces
cargo test runs the tests of every crate
Now run cargo test in the top-level add directory. In a workspace structured like this one, it runs the tests for all the crates in the workspace:
$ cargo test
Compiling add_one v0.1.0 (file:///projects/add/add_one)
Compiling adder v0.1.0 (file:///projects/add/adder)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.20s
Running unittests src/lib.rs (target/debug/deps/add_one-93c49ee75dc46543)
running 1 test
test tests::it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
The first section of the output shows that the it_works test in the add_one crate passed. The output continues on the next slide.
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
40
Chapter 14 · 14.3 Cargo Workspaces
cargo test in the workspace (continued)
Rest of the cargo test output:
Running unittests src/main.rs (target/debug/deps/adder-3a47283c568d2b6a)
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests add_one
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
- The next section shows that zero tests were found in the adder crate.
- The last section shows that zero documentation tests were found in the add_one crate.
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
41
Chapter 14 · 14.3 Cargo Workspaces
Testing one crate with cargo test -p
From the top-level directory, run the tests of one particular crate with the -p flag and the crate’s name:
$ cargo test -p add_one
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.00s
Running unittests src/lib.rs (target/debug/deps/add_one-93c49ee75dc46543)
running 1 test
test tests::it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests add_one
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
cargo test ran only the tests for the add_one crate and didn’t run the adder crate tests.
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
42
Chapter 14 · 14.3 Cargo Workspaces
Publishing workspace crates, and why workspaces
Publishing
If you publish the crates in the workspace to crates.io, each crate in the workspace must be published separately. As with cargo test, publish a particular crate of the workspace with the -p flag and the name of the crate you want to publish.
Example 14.9. For additional practice, add an add_two crate to this workspace in a similar way to the add_one crate!
When to use a workspace
- As your project grows, consider a workspace: it lets you work with smaller, easier-to-understand components than one big blob of code.
- Keeping the crates in a workspace can make coordination between them easier if they are often changed at the same time.
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
43
Chapter 14 · 14.4 Installing Binaries with cargo install
Installing binaries with cargo install
The cargo install command lets you install and use binary crates locally. It isn’t intended to replace system packages; it’s a convenient way for Rust developers to install tools that others have shared on crates.io. You can only install packages that have binary targets.
Definition 14.10 (Binary target). The runnable program created if the crate has a src/main.rs file or another file specified as a binary — as opposed to a library target, which isn’t runnable on its own but is suitable for including within other programs.
Usually, a crate’s README file says whether the crate is a library, has a binary target, or both.
All binaries installed with cargo install are stored in the installation root’s bin folder. If you installed Rust using rustup.rs and have no custom configurations, this directory is $HOME/.cargo/bin. Ensure that this directory is in your $PATH to be able to run programs you’ve installed with cargo install.
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
44
Chapter 14 · 14.4 Installing Binaries with cargo install
Example: installing ripgrep
Chapter 12 mentioned ripgrep, a Rust implementation of the grep tool for searching files. To install it, run:
$ cargo install ripgrep
Updating crates.io index
Downloaded ripgrep v14.1.1
Downloaded 1 crate (213.6 KB) in 0.40s
Installing ripgrep v14.1.1
--snip--
Compiling grep v0.3.2
Finished `release` profile [optimized + debuginfo] target(s) in 6.73s
Installing ~/.cargo/bin/rg
Installed package `ripgrep v14.1.1` (executable `rg`)
The second-to-last line of the output shows the location and the name of the installed binary, which for ripgrep is rg. As long as the installation directory is in your $PATH, you can then run rg --help and start using a faster, Rustier tool for searching files!
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
45
Chapter 14 · 14.5 Extending Cargo with Custom Commands
Extending Cargo with custom commands
Cargo is designed so that you can extend it with new subcommands without having to modify it.
Definition 14.11 (Custom Cargo command). A binary in your $PATH named cargo-something, which you can run as if it were a Cargo subcommand by running cargo something.
- Custom commands like this are also listed when you run cargo --list.
- Being able to use cargo install to install extensions and then run them just like the built-in Cargo tools is a super-convenient benefit of Cargo’s design!
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
46
Chapter 14 · Summary
Chapter summary
Sharing code with Cargo and crates.io is part of what makes the Rust ecosystem useful for many different tasks. Rust’s standard library is small and stable, but crates are easy to share, use, and improve on a timeline different from that of the language. Don’t be shy about sharing code that’s useful to you on crates.io; it’s likely to be useful to someone else as well! In this chapter:
- release profiles (dev, release) and [profile.*] overrides such as opt-level;
- /// and //! doc comments, cargo doc, doc tests, and pub use re-exports for a convenient public API;
- cargo login, required metadata, cargo publish (permanent) and cargo yank;
- workspaces: one Cargo.lock and target, path dependencies, -p to run, test or publish one crate;
- cargo install for binary crates, and cargo-something binaries as custom commands.
Remark. Next, Chapter 15 turns to smart pointers, such as Box<T>, Rc<T> and RefCell<T>.
The Rust Programming Language · Ch.14 More About Cargo and Crates.io
47