liveBook · Manning

Library crate

As explained in Rust Web Development

A library crate is a Rust crate that provides functionality through a public interface rather than creating an executable.

A library crate packages functionality behind a public interface; unlike a binary crate, it does not create an executable. In a Rust project, Cargo creates a library with `--lib` and a `lib.rs` file. section 5.1

To extract a component into a local library crate:

  • Create it with `cargo new handle-errors --lib` and move the component code into its `src/lib.rs`. section 5.1.3
  • Add the crate to the application’s `Cargo.toml` using a local path, then import its public functionality where needed. section 5.1.3
  • Update the crate’s dependencies for libraries it uses; the extracted error-handling crate, for example, depends on Warp. section 5.1.3

Extracting error handling

A web service moves its error code into a `handle-errors` library crate, adds that crate by local path, and imports its error type and handler. This removes the old module declaration and lets multiple files use the extracted functionality. section 5.1.3

Figure 5.2 After creating a new library in our application folder, we can add it to the Cargo dependencies and specify a local path; afterward, we use it as any other external library in our files.
05-02

Shows how a library in the application folder becomes a Cargo path dependency. section 5.1.3

A project can also expose its application code as a library while retaining a binary that starts the server. Public library functions can then be used by an integration-test project. section 11.3.1

How Rust Web Development covers it

How deep it goes
Defines the library–binary distinction and walks through creating a local crate, adding it as a dependency, and importing it.
Examples
Uses a local error-handling crate in a web service and a library-plus-server split for integration testing.
What it assumes
Assumes a Rust application managed with Cargo and explains how its binary-project structure differs from a library crate.
What you can do after
Build a local library crate, add it as a path dependency, and import its public functionality into an application.
How it connects
Connects library crates with binary crates, Cargo dependencies, public interfaces, and integration testing.

Also explained in

Compare how 2 books explain library crate →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust Web Development. The section links point to the parts of the book it draws on.