Skip to main content
Be Bitwise
RustRust Systems Programming

Building a Library

Building a Rust library worth using means thinking about module layout, public-API shape, docs, feature flags, and the unwritten conventions that make a crate pleasant to depend on.

Crate Structure

A typical library crate:

rust
my-crate/
Cargo.toml
src/
lib.rs # Crate root, defines public API
parser.rs # Parser module
types.rs # Type definitions
error.rs # Error types
utils.rs # Internal utilities
tests/
integration.rs # Integration tests
examples/
basic.rs # Usage examples
benches/
benchmark.rs # Benchmarks

Module organisation

rust
// src/lib.rs - the crate root defines what is public
mod parser;
mod types;
mod error;
mod utils;
// Re-export public types at the crate root for convenience
pub use types::{Config, Record, Metadata};
pub use error::{Error, Result};
pub use parser::Parser;
// The prelude pattern: common imports for users
pub mod prelude {
pub use crate::{Config, Record, Parser, Error, Result};
}
Key Concept

Re-export the important types at the crate root. Users want use my_crate::Config, not use my_crate::types::config::Config. A prelude module is the polite way to let power users grab everything in one line: use my_crate::prelude::*.

Public API Design

Follow Rust API guidelines:

rust
// Use builders for complex construction
pub struct ServerBuilder {
host: String,
port: u16,
threads: usize,
}
impl ServerBuilder {
pub fn new(host: impl Into<String>) -> Self {
ServerBuilder {
host: host.into(),
port: 8080,
threads: num_cpus::get(),
}
}
pub fn port(mut self, port: u16) -> Self {
self.port = port;
self
}
pub fn threads(mut self, n: usize) -> Self {
self.threads = n;
self
}
pub fn build(self) -> Result<Server, Error> {
Server::start(self)
}
}
// Accept generic types with Into/AsRef
pub fn process_file(path: impl AsRef<std::path::Path>) -> Result<(), Error> {
let path = path.as_ref();
// ...
Ok(())
}
// Return iterators instead of Vec
pub fn find_matches<'a>(&'a self, pattern: &'a str) -> impl Iterator<Item = &'a Record> {
self.records.iter().filter(move |r| r.matches(pattern))
}

Error Types

Make your error types tell the user what went wrong, and where:

rust
use std::fmt;
use std::io;
#[derive(Debug)]
pub enum Error {
Io(io::Error),
Parse { line: usize, message: String },
InvalidConfig(String),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Io(e) => write!(f, "I/O error: {}", e),
Error::Parse { line, message } =>
write!(f, "Parse error at line {}: {}", line, message),
Error::InvalidConfig(msg) =>
write!(f, "Invalid configuration: {}", msg),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Io(e) => Some(e),
_ => None,
}
}
}
impl From<io::Error> for Error {
fn from(e: io::Error) -> Self {
Error::Io(e)
}
}
pub type Result<T> = std::result::Result<T, Error>;

Documentation

Documentation is a first-class citizen in Rust. Doc comments compile straight to browsable HTML:

rust
/// A parser for the custom log format.
///
/// # Examples
///
/// ```
/// use my_crate::Parser;
///
/// let parser = Parser::new();
/// let entries = parser.parse("2024-01-15 INFO Starting").unwrap();
/// assert_eq!(entries.len(), 1);
/// ```
///
/// # Errors
///
/// Returns [`Error::Parse`] if the input is malformed.
pub struct Parser {
// ...
}
impl Parser {
/// Creates a new parser with default settings.
pub fn new() -> Self {
Parser { /* ... */ }
}
/// Parses a string of log entries.
///
/// Each line should follow the format: `TIMESTAMP LEVEL MESSAGE`
///
/// # Arguments
///
/// * `input` - The raw log text to parse
///
/// # Returns
///
/// A vector of parsed log entries, or an error if parsing fails.
pub fn parse(&self, input: &str) -> Result<Vec<LogEntry>> {
// ...
Ok(vec![])
}
}

Generate and view documentation:

bash
cargo doc --open

Here's a cut-down version of the crate squeezed into one file, with mod blocks standing in for the files under src/ and a real LogEntry for the parser to return. main plays a user who only knows the prelude.

Try itChange main to name my_crate::types::LogEntry directly and read the error: types is private, so the re-export is the only way in.
Rust (1.40.0)

Feature Flags

Feature flags let users pick the parts they actually want:

toml
# Cargo.toml
[features]
default = ["json"]
json = ["dep:serde", "dep:serde_json"]
async = ["dep:tokio"]
compression = ["dep:flate2"]
[dependencies]
serde = { version = "1", optional = true, features = ["derive"] }
serde_json = { version = "1", optional = true }
tokio = { version = "1", optional = true, features = ["full"] }
flate2 = { version = "1", optional = true }

The dep: prefix (Cargo 1.60 and later) says "turn on this optional dependency" without also creating a public feature with the same name. Leave it off and every optional dependency quietly becomes a feature users can switch on by itself, which is rarely what you meant.

rust
// In code:
#[cfg(feature = "json")]
pub mod json {
use serde::{Serialize, Deserialize};
pub fn to_json<T: Serialize>(value: &T) -> Result<String, serde_json::Error> {
serde_json::to_string_pretty(value)
}
}
#[cfg(feature = "async")]
pub async fn process_async(path: &str) -> Result<(), Error> {
let content = tokio::fs::read_to_string(path).await?;
// ...
Ok(())
}

Testing

rust
// Unit tests in the same file
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parser_basic() {
let parser = Parser::new();
let result = parser.parse("2024-01-15 INFO Hello");
assert!(result.is_ok());
}
#[test]
fn test_parser_error() {
let parser = Parser::new();
let result = parser.parse("invalid");
assert!(result.is_err());
}
}
// Integration tests in tests/ directory
// tests/integration.rs
use my_crate::Parser;
#[test]
fn test_full_parsing_pipeline() {
let input = std::fs::read_to_string("tests/fixtures/sample.log").unwrap();
let parser = Parser::new();
let entries = parser.parse(&input).unwrap();
assert!(!entries.is_empty());
}

Publishing to crates.io

toml
# Cargo.toml metadata for publishing
[package]
name = "my-crate"
version = "0.1.0"
edition = "2024"
description = "A fast log parser for custom formats"
license = "MIT OR Apache-2.0"
repository = "https://github.com/user/my-crate"
documentation = "https://docs.rs/my-crate"
readme = "README.md"
keywords = ["parser", "logging", "analytics"]
categories = ["command-line-utilities", "parsing"]
bash
# Dry run (check everything without publishing)
cargo publish --dry-run
# Publish
cargo publish

Semver and Versioning

Rust follows semantic versioning strictly:

  • 0.x.y: Breaking changes allowed in minor version bumps
  • 1.0.0+: Breaking changes only in major version bumps
  • Adding public API is a minor version bump
  • Bug fixes are patch version bumps

A well-shaped library makes its users productive on day one. Stick to the conventions, document generously, and don't skimp on tests.