Rust Examples
128 practical Rust code examples organized by topic. Each example includes runnable code, explanations, and key concepts.
ai-inference
AI Inference Batch Processing
Dynamic batching for AI inference in Rust using tokio channels and semaphores for high-throughput model serving.
AI Model Registry in Rust
Thread-safe model registry for serving multiple AI models in a single Rust inference server using Arc and RwLock.
LLM Token Streaming in Rust
Stream LLM tokens in real-time using Rust async channels, compatible with Server-Sent Events (SSE) and WebSocket APIs.
Vector Similarity Search in Rust
Implement cosine similarity search over embedding vectors in Rust for semantic search, RAG, and recommendation systems.
Basics
Variables, types, structs, enums, and fundamental Rust syntax.
Constants and Static
Difference between const and static variables in Rust.
Custom Struct
Define and instantiate a custom struct with named fields.
Documentation Comments
Write documentation with /// and //! comments.
Enum with Methods
Implement methods on enums.
Enums Basic
Define enums with data variants and match on them.
Formatted Print
Use format!, print!, and println! macros for formatted output.
Hello World
Print text to the standard output with println! macro.
Methods with impl
Define methods on structs using impl blocks.
Numeric Conversions
Convert between numeric types safely.
Primitive Types
Scalar and compound types in Rust: integers, floats, booleans, tuples, arrays.
Type Aliases
Use type aliases to create shorter names for complex types.
Variables and Mutability
Understand let bindings, mut keyword, and shadowing.
Ownership
Ownership, borrowing, references, and move semantics.
Borrowing
Use references to borrow values without taking ownership.
Clone and Copy
Deep copy with Clone and stack copy with Copy trait.
Closure Ownership
How closures capture values: by reference, mutable reference, or by value.
Mutable Borrow
Use mutable references to modify borrowed data.
Non-Lexical Lifetimes
Understanding how Rust determines borrow lifetimes.
Ownership and Functions
How ownership transfers when passing values to functions.
Ownership Basics
Understand Rust ownership model with move semantics.
Compound Types
Arrays, slices, tuples, strings, and Vec.
Array and Slice
Fixed-size arrays and dynamic slices in Rust.
Enum Variants
Different kinds of enum variants: unit, tuple, and struct.
String and &str
Difference between String and string slices (&str).
String Formatting
Format strings with format! macro and various specifiers.
String Manipulation
Common string operations: concat, split, replace, trim.
Tuple Destructuring
Create and destructure tuples in Rust.
Vec Basics
Create, modify, and iterate over dynamic arrays (Vec).
Vec Methods
Common Vec methods: retain, dedup, windows, chunks.
Flow Control
if/else, loops, match, and pattern matching.
For Loop with Range
Iterate over ranges with for loop.
If Else
Conditional branching with if, else if, and else.
If Let
Concise pattern matching for a single case.
Labeled Loops
Use labels with break and continue for nested loops.
Loop
Infinite loops with break and continue.
Match Basic
Pattern matching with match expression.
Match Guards
Add conditions to match arms with guards.
Match with Enums
Pattern match on enum variants with data extraction.
While Let
Loop with pattern matching at the top.
While Loop
Loop with a condition check at the top.
Functions
Functions, closures, and higher-order functions.
Closures Basic
Anonymous functions that capture their environment.
Diverging Functions
Functions that never return using -> ! (never type).
Function Pointers
Use function pointers (fn) as arguments and return values.
Functions Basic
Define and call functions with parameters and return values.
Higher-Order Functions
Functions that take or return other functions.
Returning Closures
Return closures from functions using impl Fn or Box<dyn Fn>.
Generics
Generic types, trait bounds, and type parameters.
Generic Enums
Standard library generic enums like Option and Result.
Generic Function
Write functions that work with multiple types using generics.
Generic Struct
Define structs with generic type parameters.
Multiple Generic Parameters
Use multiple type parameters in functions and structs.
Trait Bounds
Constrain generic types with trait bounds.
Traits
Trait definition, implementation, and trait objects.
Associated Types
Define associated types in traits for cleaner generic code.
Derive Macros
Automatically implement common traits with derive.
From and Into
Type conversions with From and Into traits.
Implementing Display
Implement the Display trait for custom types.
Operator Overloading
Implement operator traits like Add, Mul, Display.
Trait Basic
Define and implement traits for custom types.
Trait Default Implementation
Provide default behavior for trait methods.
Trait Objects (dyn Trait)
Use trait objects for dynamic dispatch with dyn keyword.
Error Handling
Result, Option, ? operator, and custom errors.
Custom Error Type
Define custom error types with thiserror or manually.
Map and Transform Errors
Transform error types with map_err and and_then.
Option Basic
Handle optional values with Option<T>.
Question Mark Operator
Use ? to propagate errors concisely.
Result Basic
Handle errors with Result<T, E> type.
Result Combinators
Chain operations on Result with map, and_then, or_else.
Unwrap and Expect
Quick error handling with unwrap and expect.
Collections
HashMap, HashSet, BTreeMap, and Vec operations.
BTreeMap
Sorted key-value map with B-tree implementation.
BTreeMap Range Queries
Query ranges in sorted maps with BTreeMap.
Group By with HashMap
Group items by key using HashMap.
HashMap Advanced Operations
Merge, update, and transform HashMaps.
HashMap Basic
Create and use hash maps for key-value storage.
HashMap Entry API
Use the entry API for conditional insert and update.
HashSet Basic
Use HashSets for unique collections and set operations.
Sorting Vectors
Sort vectors with sort, sort_by, and sort_unstable.
VecDeque
Double-ended queue with efficient push/pop from both ends.
Concurrency
Threads, channels, Arc, Mutex, and atomics.
Arc and Mutex
Share state between threads safely with Arc<Mutex<T>>.
Atomic Types
Use atomic types for lock-free concurrent programming.
Barrier Synchronization
Synchronize multiple threads with Barrier.
Channel Basic
Send messages between threads with channels.
RwLock
Read-write lock for concurrent reads and exclusive writes.
Thread Basic
Spawn threads and join them.
Thread Pool Pattern
Simple thread pool pattern with channels.
Thread with Move
Transfer ownership to threads with move closures.
Async
async/await, futures, and asynchronous programming.
Smart Pointers
Box, Rc, Cell, RefCell, and interior mutability.
Iterators
Iterator trait, adaptors, and lazy evaluation.
Custom Iterator
Implement the Iterator trait for custom types.
FlatMap and Flatten
Flatten nested iterators with flat_map and flatten.
Iterator Basic
Use iterator adaptors: map, filter, collect.
Iterator Chain
Chain multiple iterator operations together.
Iterator Enumerate
Get index and value with enumerate.
Iterator Zip
Combine two iterators with zip.
Patterns
Pattern matching, destructuring, and guards.
Modules
Modules, imports, and code organization.
Macros
Declarative macros and macro_rules!.
Unsafe
Unsafe code, raw pointers, and FFI.
Lifetimes
Lifetime annotations and lifetime elision.
Testing
Unit tests, integration tests, and test organization.
File I/O
Reading and writing files with std::fs.
Serialization
JSON and data serialization with serde.
CLI
Command line argument parsing and CLI tools.