Index of Examples
Algorithms
Randomness
| fastrand
| | |
Sorting
Recipe | Crates | Categories |
---|---|---|
Sort a vector of integers | ||
Sort a vector of floats | ||
Sort a vector of structs |
Asynchronous
Async
Recipe | Crates | Categories |
---|---|---|
Basic example | ||
Differences with other languages | ||
Which crate provides what? | ||
Async runtimes |
Async and Blocking
Async Channels
Recipe | Crates | Categories |
---|---|---|
OneShot | ||
Multiple Producer, Single Consumer |
Async Traits
Recipe | Crates | Categories |
---|---|---|
Async traits |
Futures
Recipe | Crates | Categories |
---|---|---|
Selecting futures | ||
Joining futures | ||
Map, then, either, flatten |
Streams
Recipe | Crates | Categories |
---|---|---|
Streams |
Tokio
Recipe | Crates | Categories |
---|---|---|
Basics | ||
Join | ||
Spawning | ||
IO | ||
Graceful shutdown |
Authentication
Basic Authentication
Recipe | Crates | Categories |
---|---|---|
Perform a basic HTTP authentication |
Command Line Interface
ANSI Terminal
| ansiterm
| | |
| anstream
| | |
| anstyle
| | |
| console
| | |
| owo-colors
| | |
| stylish
| | |
| termcolor
| | |
| yansi
| | |
| termion
| | |
Arguments
Recipe | Crates | Categories |
---|---|---|
Using clap's builder API | ||
Using clap 's derive API | ||
lexopt | ||
pico-args |
| structopt
| | |
TUI
Recipe | Crates | Categories |
---|---|---|
Build complex TUI |
User Interaction
Recipe | Crates | Categories |
---|---|---|
Ask for confirmation, selection, text input | ||
Display progress bars and spinners |
Command Line Utilities
Filesystem
Networking
Recipe | Crates | Categories |
---|---|---|
gping |
Shells
Compression
tar
Recipe | Crates | Categories |
---|---|---|
Compress a directory into a tarball | ||
Decompress a tarball | ||
Decompress a tarball while removing a prefix from the paths |
Concurrency
Concurrent Data Structures
Recipe | Crates | Categories |
---|---|---|
Bounded multi-producer multi-consumer queue | ||
dashmap | ||
flurry |
Crossbeam
Recipe | Crates | Categories |
---|---|---|
Spawn a short-lived thread | ||
Create a parallel pipeline | ||
Pass data between two threads |
Data Parallelism
Explicit Threads
Recipe | Crates | Categories |
---|---|---|
Use spawn, join | [] | |
Use scoped threads |
Message Passing
Recipe | Crates | Categories |
---|---|---|
Multiple producers, single consumer | ||
crossbeam-channel | ||
flume | ||
tokio |
Send
Recipe | Crates | Categories |
---|---|---|
Send and Sync traits |
Shared State
Recipe | Crates | Categories |
---|---|---|
Maintain a global mutable state | ||
Mutexes | ||
parking_lot | ||
Atomics | ||
arc-swap |
Threadpool
Recipe | Crates | Categories |
---|---|---|
Calculate the SHA256 of ISO files concurrently | ||
Draw a fractal, dispatching work to a thread pool |
Config
Configuration
Environment Variables
Cryptography
Encryption
Recipe | Crates | Categories |
---|---|---|
Salt and hash a password with PBKDF2 |
Hashing
Data Structures
Bitfield
Recipe | Crates | Categories |
---|---|---|
Define and operate on a type represented as a bitfield | ||
flagset |
Maps
Recipe | Crates | Categories |
---|---|---|
Store data in an insertion-ordered map | ||
Store data in a multimap | ||
slotmap |
Stack Allocated Arrays
UUID
Recipe | Crates | Categories |
---|---|---|
Generate and parse UUIDs |
Database
Connection Pool
Recipe | Crates | Categories |
---|---|---|
Create a connection pool |
NoSQL
Recipe | Crates | Categories |
---|---|---|
Connect to MongoDB | ||
Connect to Redis |
Postgres
Recipe | Crates | Categories |
---|---|---|
Create tables in a Postgres database | ||
Insert and query data | ||
Aggregate data | ||
tokio-postgres | ||
cornucopia for postgres | cornucopia-rs⮳ |
Query Builders Orms
Search
Recipe | Crates | Categories |
---|---|---|
Connect to Elasticsearch | ||
infisearch | ||
stork-search | ||
minisearch | ||
typesense | ||
tinysearch |
SQLite
Recipe | Crates | Categories |
---|---|---|
Create a SQLite database | ||
Insert and select data | ||
Using transactions |
Date and Time
Duration
Recipe | Crates | Categories |
---|---|---|
Measure the elapsed time between two code sections | ||
Perform checked date and time calculations | ||
Convert a local time to another timezone |
Parse
Recipe | Crates | Categories |
---|---|---|
Examine the date and time | ||
Convert date to UNIX timestamp and vice versa | ||
Display formatted date and time | ||
Parse string into DateTime struct |
Time
Recipe | Crates | Categories |
---|---|---|
Use the time crate |
Cargo
Cargo
Recipe | Crates | Categories |
---|---|---|
Basic cargo usage | ||
Cargo.toml and lock files |
Crate Registries
Recipe | Crates | Categories |
---|---|---|
Crate registries | crates.io⮳ |
Package Layout
Recipe | Crates | Categories |
---|---|---|
Package layout |
Documentation
Badges
Documentation
Recipe | Crates | Categories |
---|---|---|
Document your code | ||
Create module- or crate-level documentation |
mdBook
| mdbook-cmdrun
| | |
| Create a journal with mdbook-journal
| | |
| Check links with mdbook-linkcheck
| | |
| mdbook-pagetoc
| | |
| Hide entire chapters with mdbook-private
| | |
| Hide pages with mdbook-hide
| | |
| Create pages from a template with mdbook-tera
| | |
| mdbook-theme
| | |
| mdbook-toc
| | |
| Test code in your mdbook
| Byron-termbook | |
| Replace text in chapters with yapp
| | |
Formatting
Formatting
Recipe | Crates | Categories |
---|---|---|
Format your Rust code with rustfmt | ||
Configure rustfmt | ||
Use attributes to skip code formatting in your code |
Installation
Install
Recipe | Crates | Categories |
---|---|---|
Build and install a Rust binary with cargo install | ||
Install a Rust binary with cargo binstall |
Rustup
Recipe | Crates | Categories |
---|---|---|
Install and manage Rust toolchains with rustup |
Other
Code Build
Recipe | Crates | Categories |
---|---|---|
Save and run project-specific commands with the just command runner | ||
Check your Rust code in the background |
Code Verification
Recipe | Crates | Categories |
---|---|---|
Verify your Rust code | {{hi:kani}} |
miri
Recipe | Crates | Categories |
---|---|---|
Install the miri interpreter | ||
Detect undefined behavior with the miri interpreter |
Other
Recipe | Crates | Categories |
---|---|---|
Search for Rust APIs | roogle | |
Deploy your Rust code on shuttle.rs | shuttle.rs | |
Minimize Rust binary sizes | {{#crate }} | |
Generate Rust code | {{#crate }} |
Versioning
Versioning
Development Tools: Build Utils
Build Utils
Recipe | Crates | Categories |
---|---|---|
Compile and link statically to a bundled C library | ||
Compile and link statically to a bundled C++ library | ||
Compile a C library while setting custom defines |
Development Tools: Cargo Plugins
Auditing
Building
Recipe | Crates | Categories |
---|---|---|
cargo make | ||
Use devx | ||
Make Rust a better bash with xshell |
Code Formatting Linting
Recipe | Crates | Categories |
---|---|---|
Format your code | ||
Lint your code | ||
Fix compiler warnings automatically | ||
Format or lint your code before committing it |
Cross Compiling
Recipe | Crates | Categories |
---|---|---|
Cross-compile using zig as the linker |
Maintaining
Recipe | Crates | Categories |
---|---|---|
Edit Cargo.toml | ||
Find unused dependencies | ||
Detect dependencies that are out of date | ||
Lint your crate API changes for semver violations | ||
Manage the cargo cache |
| cargo expand
| | |
| cargo hack
| | |
Performance
Recipe | Crates | Categories |
---|---|---|
Configure your cargo project for maximum performance, fast compile times or minimal binary size | ||
cargo hakari |
Watching For Changes
Recipe | Crates | Categories |
---|---|---|
cargo watch | ||
cargo limit |
Writing
Recipe | Crates | Categories |
---|---|---|
Generate a Rust project from a template | ||
Quickly open the crates.io or docs.rs page for the latest version of a crate |
Development Tools: Debugging
Alternatives
Recipe | Crates | Categories |
---|---|---|
log | ||
slog | ||
log4rs | ||
env_logger | ||
OpenTelemetry | OpenTelemetry Rust documentation⮳ | |
OpenObserve | OpenObserve⮳ |
Config Log
Recipe | Crates | Categories |
---|---|---|
Enable log levels per module | ||
Use a custom environment variable to set up logging | ||
Include a timestamp in log messages | ||
Log messages to a custom location |
Diagnostic Functions
Recipe | Crates | Categories |
---|---|---|
Get the type name of the pointed-to value |
Log
Recipe | Crates | Categories |
---|---|---|
Log a debug message to the console | ||
Log an error message to the console | ||
Log to stdout instead of stderr | ||
Log messages with a custom logger | ||
Log to the Unix syslog |
Tracing
Recipe | Crates | Categories |
---|---|---|
Initialize the logger | ||
Enable basic tracing | ||
Combine layers | ||
Configure a custom event formatter | ||
Events | ||
Spans | ||
Add tracing spans to functions | ||
See also |
Encoding
Binary Encoders
Recipe | Crates | Categories |
---|---|---|
bincode | ||
CBOR with ciborium | ||
prost | ||
protobuf | ||
MessagePack with rmp-serde |
Complex
Recipe | Crates | Categories |
---|---|---|
Serialize and deserialize unstructured JSON | ||
Deserialize a TOML configuration file | ||
Read and write integers in little-endian byte order |
CSV
Serde
Recipe | Crates | Categories |
---|---|---|
Serialize JSON | ||
monostate | ||
serde-ignored |
Strings
Recipe | Crates | Categories |
---|---|---|
Percent-encode a string | ||
Encode a string as application/x-www-form-urlencoded | ||
Encode and decode hexadecimal | ||
Encode and decode base64 |
Typecasts
Filesystem
cwd
Recipe | Crates | Categories |
---|---|---|
Get the current working directory |
Dir
| globset
| | |
File Watching
Recipe | Crates | Categories |
---|---|---|
Watch files or directories and execute a function when they change |
Ignore
Recipe | Crates | Categories |
---|---|---|
Walk the filesystem while respecting ignore files |
Read-Write
Recipe | Crates | Categories |
---|---|---|
Read lines of strings from a file | ||
Avoid writing and reading from the same file | ||
Access a file randomly using a memory map |
Tempfile
Recipe | Crates | Categories |
---|---|---|
Create temporary files or temporary directories |
User Directories
Recipe | Crates | Categories |
---|---|---|
dirs | ||
directories |
Hardware Support
Processor
Recipe | Crates | Categories |
---|---|---|
Check the number of logical cpu cores |
Mathematics
Additional Numeric Types
Recipe | Crates | Categories |
---|---|---|
Abstract over different number types | ||
Use big integers | ||
Use big decimals | ||
Sort floats |
| num-bigint
| | |
| num
| | |
| rug
| | |
Complex Numbers
Recipe | Crates | Categories |
---|---|---|
Create complex numbers | ||
Add complex numbers | ||
Use mathematical functions on complex numbers |
Linear Algebra
Recipe | Crates | Categories |
---|---|---|
Calculate vector norms | ||
Add matrices | ||
Multiply matrices | ||
Multiply a scalar with a vector and a matrix | ||
Invert a matrix | ||
Compare vectors | ||
(De)serialize a matrix |
Statistics
Recipe | Crates | Categories |
---|---|---|
Calculate measures of central tendency | ||
Compute the standard deviation |
Trigonometry
Recipe | Crates | Categories |
---|---|---|
Calculate the side length of a triangle | ||
Verify that tan is equal to sin divided by cos | ||
Calculate the distance between two points on Earth |
Memory Management
Global Static
Recipe | Crates | Categories |
---|---|---|
Declare lazily evaluated constants |
Lazy Initialization
Recipe | Crates | Categories |
---|---|---|
std | ||
once_cell | ||
lazy_static |
OS
External
Low Level System Calls
Recipe | Crates | Categories |
---|---|---|
Call libc , the C standard library |
Rust OS
Recipe | Crates | Categories |
---|---|---|
Host containers with bottlerocket | ||
Run a Rust operating system on your computer with Redox |
Rust Patterns
Builder Pattern
Recipe | Crates | Categories |
---|---|---|
bon | ||
derive_builder | ||
typed-builder |
Design Patterns
Recipe | Crates | Categories |
---|---|---|
Implement an abstract factory | {{#crate }} | |
Clone a struct storing a boxed trait object |
| Implement the typestate pattern in Rust | {{#crate }} | |
Error Customization
Recipe | Crates | Categories |
---|---|---|
anyhow | ||
thisError | ||
miette | ||
color-eyre |
Error Handling
Functional Programming
Recipe | Crates | Categories |
---|---|---|
Compose iterators |
Rust Idioms
Recipe | Crates | Categories |
---|---|---|
Rust idioms and patterns | {{#crate }} |
Template Engine
Tera
Recipe | Crates | Categories |
---|---|---|
Create HTML files from a template |
Tinytemplate
Recipe | Crates | Categories |
---|---|---|
Create Markdown fragments from a template |
Text Editors
IDEs
Recipe | Crates | Categories |
---|---|---|
Write Rust code with VS Code | VS Code⮳ | |
Write Rust code with the zed editor |
| Use the Helix Editor | Helix editor⮳ | |
| Write Rust code with RustRover | RustRover
⮳ | |
| Use neovim
| Neovim⮳ | |
Text Processing
Regex
| Use regular expressions with backreferences and lookarounds | | |
Regex2
Recipe | Crates | Categories |
---|---|---|
Longer Regex Example |
String Concat
Recipe | Crates | Categories |
---|---|---|
Compare string concatenation methods |
String Parsing
Recipe | Crates | Categories |
---|---|---|
Collect unicode graphemes | ||
Implement the FromStr trait for a custom struct |
Web Programming
Mime
Recipe | Crates | Categories |
---|---|---|
Get a MIME type from a string | ||
Get a MIME type from a filename | ||
Parse the MIME type of a HTTP response |
Scraping
Recipe | Crates | Categories |
---|---|---|
Extract all links from the HTML of a webpage | ||
Check a webpage for broken links | ||
Extract all unique links from a MediaWiki markup |
Url
Web Programming: HTTP Client
APIs
Recipe | Crates | Categories |
---|---|---|
Query the GitHub API | ||
Check if an API resource exists | ||
Create and delete a Gist with the GitHub API | ||
Consume a paginated RESTful API | ||
Handle a rate-limited API |
Download
Recipe | Crates | Categories |
---|---|---|
Download a file to a temporary directory | ||
Make a partial download with HTTP range headers | ||
POST a file to paste.rs |
HTTP Clients
Requests
Recipe | Crates | Categories |
---|---|---|
Make a HTTP GET request | ||
Make a HTTP GET request asynchronously | ||
Set custom headers and URL parameters for a REST request |
Web Programming: HTTP Server
actix
Recipe | Crates | Categories |
---|---|---|
Create a web server with Actix Web |
axum
Recipe | Crates | Categories |
---|---|---|
Create a web server with axum |
Batteries-Included Frameworks
Recipe | Crates | Categories |
---|---|---|
loco | ||
Rust on Nails | Rust on Nails⮳ |
CORS
Recipe | Crates | Categories |
---|---|---|
Implement CORS |
GraphQL
Recipe | Crates | Categories |
---|---|---|
Create a GraphQL endpoint |
gRPC
Recipe | Crates | Categories |
---|---|---|
Implement gRPC |
hyper
Recipe | Crates | Categories |
---|---|---|
Implement an HTTP API with hyper |
Middleware
Recipe | Crates | Categories |
---|---|---|
tower | ||
tower-http | ||
Investigate alternatives to tower |
Other Frameworks
Recipe | Crates | Categories |
---|---|---|
Implement a HTTP server using rocket | ||
leptos |
Static Website Generators
Recipe | Crates | Categories |
---|---|---|
Create a simple website using a static website generator |
Contributing
API Documentation
Generate the docs.rs Documentation |
Using a Dev Container feature |
Other methods to preview the documentation HTML |
Development Editing
Dev Container Docker
Dev Environment Setup
Optional Preprocessors
Publication
Repo Structure
Topics of Interest
Crates
Language
Attributes
Attributes |
Lint attributes |
Automatically derive common traits |
Mark as must use |
Mark as deprecated |
Compile conditionally |
Closures
Control Flow
Enums
Functions
Generics
Iterators
Lifetimes
Macros
Main
Match
Modules
Ownership Borrowing
Rust Install
Simple Data Types
Slices
Structs
Traits
Trait Objects
Variables and Constants
Links
Blogs Podcasts Meetups
Books
Companies
Example Code
Learning Rust |
Rust Cheatsheets |
Comparison to other languages |
Books |
Example code |
Rust Blogs & Podcasts |
Newsletters |
Meetups |
Companies |
Lists of Rust links |
Learning
Links
Rust Cheatsheets
Standard Library
AsRef
Recipe | Crates |
---|---|
AsRef and &T |
Cow
Recipe | Crates |
---|---|
Convert Cow to &str | |
Convert Cow to String |
Derive
Hashmaps
Recipe | Crates |
---|---|
Hashmaps |
Option
Recipe | Crates |
---|---|
Option | |
Use adapters when working with references | |
Extract the value contained in Option | |
Use combinators |
Result
Recipe | Crates |
---|---|
Result |
Smart Pointers
Strings
Recipe | Crates |
---|---|
String | |
Placeholders | |
Concatenate strings |
Vectors
Recipe | Crates |
---|---|
Vec |