liveBook · Manning

Library crate

As explained in Refactoring to Rust

A library crate is a Rust crate that provides code for inclusion by another executable rather than defining a directly executable program.

A library crate provides Rust code for inclusion by another executable. It contains lib.rs and cannot run by itself, unlike an executable crate with main.rs. section 6.4

Convert an executable crate into a library crate incrementally:

  • Rename main.rs to lib.rs. section 6.4
  • Delete the main function. section 6.4
  • Add integration glue when another environment, such as Python, will load the library. section 6.4

Rust library used from Python

A rust_json crate defines sum in lib.rs, exposes it with PyO3, and registers it in a Python module. After maturin develop, Python imports rust_json and calls rust_json.sum(...). section 6.4

[package]
name = "rust_json"
version = "0.1.0"
edition = "2018"

[lib]  #1
crate-type = ["cdylib"]

[dependencies]
serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
pyo3 = { version = "0.14", features = ["extension-module"] }  #2

The Cargo configuration shows a library target using the cdylib crate type and PyO3's extension-module feature. section 6.4

How Refactoring to Rust covers it

How deep it goes
Defines lib.rs versus main.rs and demonstrates conversion for Python integration, without developing broader library design.
Examples
Uses the rust_json crate, lib.rs, a PyO3 module, Python imports, and a JSON-lines processing program.
What it assumes
Assumes familiarity with an executable crate and teaches the crate-type distinction through a direct file migration.
What you can do after
Apply it via PyO3 and Maturin to expose Rust functions through an importable Python module.
How it connects
Connects library crates with executable crates, Cargo, PyO3, Python extension modules, and Maturin.

Related concepts

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