Cookin' with Rust

This Rust Cookbook is a collection of simple examples that demonstrate good practices to accomplish common programming tasks, using the crates of the Rust ecosystem.

Read more about Rust Cookbook, including tips for how to read the book, how to use the examples, and notes on conventions.


This project is intended to be easy for new Rust programmers to contribute to, and an easy way to get involved with the Rust community. It needs and welcomes help. For details see


Recipe Crates Categories
Generate random numbers rand-badge cat-science-badge
Generate random numbers within a range rand-badge cat-science-badge
Generate random numbers with given distribution rand-badge cat-science-badge
Generate random values of a custom type rand-badge cat-science-badge
Create random passwords from a set of alphanumeric characters rand-badge cat-os-badge
Create random passwords from a set of user-defined characters rand-badge cat-os-badge
Sort a Vector of Integers std-badge cat-science-badge
Sort a Vector of Floats std-badge cat-science-badge
Sort a Vector of Structs std-badge cat-science-badge

Command Line

Recipe Crates Categories
Parse command line arguments clap-badge cat-command-line-badge
ANSI Terminal ansi_term-badge cat-command-line-badge


Recipe Crates Categories
Decompress a tarball flate2-badge tar-badge cat-compression-badge
Compress a directory into a tarball flate2-badge tar-badge cat-compression-badge
Decompress a tarball while removing a prefix from the paths flate2-badge tar-badge cat-compression-badge


Recipe Crates Categories
Spawn a short-lived thread crossbeam-badge cat-concurrency-badge
Pass data between two threads crossbeam-badge cat-concurrency-badge
Maintain global mutable state lazy_static-badge cat-rust-patterns-badge
Calculate SHA1 sum of *.iso files concurrently threadpool-badge walkdir-badge num_cpus-badge ring-badge cat-concurrency-badgecat-filesystem-badge
Draw fractal dispatching work to a thread pool threadpool-badge num-badge num_cpus-badge image-badge cat-concurrency-badgecat-science-badgecat-rendering-badge
Mutate the elements of an array in parallel rayon-badge cat-concurrency-badge
Test in parallel if any or all elements of a collection match a given predicate rayon-badge cat-concurrency-badge
Search items using given predicate in parallel rayon-badge cat-concurrency-badge
Sort a vector in parallel rayon-badge rand-badge cat-concurrency-badge
Map-reduce in parallel rayon-badge cat-concurrency-badge
Generate jpg thumbnails in parallel rayon-badge glob-badge image-badge cat-concurrency-badgecat-filesystem-badge


Recipe Crates Categories
Calculate the SHA-256 digest of a file ring-badge data-encoding-badge cat-cryptography-badge
Sign and verify a message with an HMAC digest ring-badge cat-cryptography-badge
Salt and hash a password with PBKDF2 ring-badge data-encoding-badge cat-cryptography-badge

Data Structures

Recipe Crates Categories
Define and operate on a type represented as a bitfield bitflags-badge cat-no-std-badge


Recipe Crates Categories
Create a SQLite database rusqlite-badge cat-database-badge
Insert and Query data rusqlite-badge cat-database-badge
Create tables in a Postgres database postgres-badge cat-database-badge
Insert and Query data postgres-badge cat-database-badge
Aggregate data postgres-badge cat-database-badge

Date and Time

Recipe Crates Categories
Measure elapsed time std-badge cat-time-badge
Perform checked date and time calculations chrono-badge cat-date-and-time-badge
Convert a local time to another timezone chrono-badge cat-date-and-time-badge
Examine the date and time chrono-badge cat-date-and-time-badge
Convert date to UNIX timestamp and vice versa chrono-badge cat-date-and-time-badge
Display formatted date and time chrono-badge cat-date-and-time-badge
Parse string into DateTime struct chrono-badge cat-date-and-time-badge

Development Tools


Recipe Crates Categories
Log a debug message to the console log-badge env_logger-badge cat-debugging-badge
Log an error message to the console log-badge env_logger-badge cat-debugging-badge
Log to stdout instead of stderr log-badge env_logger-badge cat-debugging-badge
Log messages with a custom logger log-badge cat-debugging-badge
Log to the Unix syslog log-badge syslog-badge cat-debugging-badge
Enable log levels per module log-badge env_logger-badge cat-debugging-badge
Use a custom environment variable to set up logging log-badge env_logger-badge cat-debugging-badge
Include timestamp in log messages log-badge env_logger-badge chrono-badge cat-debugging-badge
Log messages to a custom location log-badge log4rs-badge cat-debugging-badge


Recipe Crates Categories
Parse and increment a version string semver-badge cat-config-badge
Parse a complex version string semver-badge cat-config-badge
Check if given version is pre-release semver-badge cat-config-badge
Find the latest version satisfying given range semver-badge cat-config-badge
Check external command version for compatibility semver-badge cat-text-processing-badge cat-os-badge

Build Time

Recipe Crates Categories
Compile and link statically to a bundled C library cc-badge cat-development-tools-badge
Compile and link statically to a bundled C++ library cc-badge cat-development-tools-badge
Compile a C library while setting custom defines cc-badge cat-development-tools-badge


Recipe Crates Categories
Percent-encode a string url-badge cat-encoding-badge
Encode a string as application/x-www-form-urlencoded url-badge cat-encoding-badge
Encode and decode hex data-encoding-badge cat-encoding-badge
Encode and decode base64 base64-badge cat-encoding-badge
Read CSV records csv-badge cat-encoding-badge
Read CSV records with different delimiter csv-badge cat-encoding-badge
Filter CSV records matching a predicate csv-badge cat-encoding-badge
Handle invalid CSV data with Serde csv-badge serde-badge cat-encoding-badge
Serialize records to CSV csv-badge cat-encoding-badge
Serialize records to CSV using Serde csv-badge serde-badge cat-encoding-badge
Transform one column of a CSV file csv-badge serde-badge cat-encoding-badge
Serialize and deserialize unstructured JSON serde-json-badge cat-encoding-badge
Deserialize a TOML configuration file toml-badge cat-encoding-badge
Read and write integers in little-endian byte order byteorder-badge cat-encoding-badge

File System

Recipe Crates Categories
Read lines of strings from a file std-badge cat-filesystem-badge
Avoid writing and reading from a same file same_file-badge cat-filesystem-badge
Access a file randomly using a memory map memmap-badge cat-filesystem-badge
File names that have been modified in the last 24 hours std-badge cat-filesystem-badge cat-os-badge
Find loops for a given path same_file-badge cat-filesystem-badge
Recursively find duplicate file names walkdir-badge cat-filesystem-badge
Recursively find all files with given predicate walkdir-badge cat-filesystem-badge
Traverse directories while skipping dotfiles walkdir-badge cat-filesystem-badge
Recursively calculate file sizes at given depth walkdir-badge cat-filesystem-badge
Find all png files recursively glob-badge cat-filesystem-badge
Find all files with given pattern ignoring filename case glob-badge cat-filesystem-badge

Hardware Support

Recipe Crates Categories
Check number of logical cpu cores num_cpus-badge cat-hardware-support-badge

Memory Management

Recipe Crates Categories
Declare lazily evaluated constant lazy_static-badge cat-caching-badge cat-rust-patterns-badge


Recipe Crates Categories
Listen on unused port TCP/IP std-badge cat-net-badge

Operating System

Recipe Crates Categories
Run an external command and process stdout regex-badge cat-os-badge cat-text-processing-badge
Run an external command passing it stdin and check for an error code regex-badge cat-os-badge cat-text-processing-badge
Run piped external commands std-badge cat-os-badge
Redirect both stdout and stderr of child process to the same file std-badge cat-os-badge
Continuously process child process' outputs std-badge cat-os-badgecat-text-processing-badge



Recipe Crates Categories
Vector Sum ndarray-badge cat-science-badge
Vector Norm ndarray-badge cat-science-badge
Adding matrices ndarray-badge cat-science-badge
Multiplying matrices ndarray-badge cat-science-badge
Multiply a scalar with a vector with a matrix ndarray-badge cat-science-badge
Invert matrix nalgebra-badge cat-science-badge
Calculating the side length of a triangle std-badge cat-science-badge
Verifying tan is equal to sin divided by cos std-badge cat-science-badge
Distance between two points on the Earth std-badge cat-science-badge
Creating complex numbers num-badge cat-science-badge
Adding complex numbers num-badge cat-science-badge
Mathematical functions on complex numbers num-badge cat-science-badge
Measures of central tendency std-badge cat-science-badge
Computing standard deviation std-badge cat-science-badge
Big integers num-badge cat-science-badge

Text Processing

Recipe Crates Categories
Collect Unicode Graphemes unicode-segmentation-badge cat-encoding-badge
Verify and extract login from an email address regex-badge lazy_static-badge cat-text-processing-badge
Extract a list of unique #Hashtags from a text regex-badge lazy_static-badge cat-text-processing-badge
Extract phone numbers from text regex-badge cat-text-processing-badge
Filter a log file by matching multiple regular expressions regex-badge cat-text-processing-badge
Replace all occurrences of one text pattern with another pattern. regex-badge lazy_static-badge cat-text-processing-badge
Implement the FromStr trait for a custom struct std-badge cat-text-processing-badge

Web Programming

Scraping Web Pages

Recipe Crates Categories
Extract all links from a webpage HTML reqwest-badge select-badge cat-net-badge
Check webpage for broken links reqwest-badge select-badge url-badge cat-net-badge
Extract all unique links from a MediaWiki markup reqwest-badge regex-badge cat-net-badge

Uniform Resource Locations (URL)

Recipe Crates Categories
Parse a URL from a string to a Url type url-badge cat-net-badge
Create a base URL by removing path segments url-badge cat-net-badge
Create new URLs from a base URL url-badge cat-net-badge
Extract the URL origin (scheme / host / port) url-badge cat-net-badge
Remove fragment identifiers and query pairs from a URL url-badge cat-net-badge

Media Types (MIME)

Recipe Crates Categories
Get MIME type from string mime-badge cat-encoding-badge
Get MIME type from filename mime-badge cat-encoding-badge
Parse the MIME type of a HTTP response mime-badge reqwest-badge cat-net-badge cat-encoding-badge


Recipe Crates Categories
Make a HTTP GET request reqwest-badge cat-net-badge
Query the GitHub API reqwest-badge serde-badge cat-net-badge cat-encoding-badge
Check if an API resource exists reqwest-badge cat-net-badge
Create and delete Gist with GitHub API reqwest-badge serde-badge cat-net-badge cat-encoding-badge
Consume a paginated RESTful API reqwest-badge serde-badge cat-net-badge cat-encoding-badge
Download a file to a temporary directory reqwest-badge tempdir-badge cat-net-badge cat-filesystem-badge
Make a partial download with HTTP range headers reqwest-badge cat-net-badge
POST a file to paste-rs reqwest-badge cat-net-badge