Rust Examples
78 practical Rust code examples organized by topic. Each example includes runnable code, explanations, and key concepts.
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.
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.
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.
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.
Mutable Borrow
Use mutable references to modify borrowed data.
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.
String and &str
Difference between String and string slices (&str).
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).
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.
Loop
Infinite loops with break and continue.
Match Basic
Pattern matching with match expression.
Match Guards
Add conditions to match arms with guards.
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.
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.
Traits
Trait definition, implementation, and trait objects.
Derive Macros
Automatically implement common traits with derive.
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.
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.
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.
Group By with HashMap
Group items by key using HashMap.
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.
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.
Channel Basic
Send messages between threads with channels.
Thread Basic
Spawn threads and join them.
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.
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.