0 day streak
Code library

Intermediate Rust exercises

Read these Intermediate Rust snippets line by line — each one comes with a written breakdown of what the code does and why.

Rust · Intermediate

Functional Iterator Adapters

Iterators in Rust are lazy and powerful. 'filter' and 'map' allow for functional-style data transformation without unnecessary intermediate allocations.

PerformanceBest Practices
Open snippet →
Rust · Intermediate

Generic Bounds with Traits

Generic bounds allow you to restrict a generic type so that it must implement specific behaviors (traits). This ensures the function can call the required methods safely.

SyntaxFunctions
Open snippet →
Rust · Intermediate

Basic Lifetime Annotations

Lifetimes ensure that references remain valid as long as they are needed. Annotating a struct with '<'a>' tells the compiler the struct cannot outlive the reference it holds.

Memory ManagementSyntax
Open snippet →
Rust · Intermediate

Dereferencing Raw Pointers in Unsafe Rust

Raw pointers (*const T and *mut T) allow you to bypass Rust's ownership and borrowing rules. Dereferencing them is considered unsafe because the compiler cannot guarantee the pointer is valid or th…

Memory ManagementSyntax
Open snippet →
Rust · Intermediate

Efficient Map Updates with the Entry API

The Entry API allows you to check for a key's existence and perform an operation in a single step, avoiding double lookups and providing a more expressive way to handle conditional insertion.

PerformanceFunctions
Open snippet →
Rust · Intermediate

Interior Mutability with RefCell

RefCell<T> provides 'interior mutability', a pattern allowing you to mutate data even when you have an immutable reference to that data. Borrowing rules are enforced at runtime rather than compile…

Memory ManagementBest Practices
Open snippet →
Rust · Intermediate

Capturing Environment with 'move' Closures

The 'move' keyword forces a closure to take ownership of the variables it captures from the environment, rather than just borrowing them. This is often required when passing closures to new threads.

FunctionsSyntax
Open snippet →
Rust · Intermediate

Option<T> for Null Safety

Rust has no null values. Instead, Option<T> represents optional values: Some(T) contains a value, None represents absence. This makes null pointer exceptions impossible at compile time. The if let…

Error HandlingData Types
Open snippet →
Rust · Intermediate

Iterator Chains with Closures

Rust iterators are lazy — they do nothing until consumed. Methods like filter, map, and take are adaptors that transform iterators without executing. The collect method consumes the iterator and pr…

SyntaxFunctions
Open snippet →
Rust · Intermediate

Struct Methods with Impl

impl blocks define methods on structs. &self borrows the struct immutably, &mut self borrows mutably, and no self creates an associated function (constructor). Self refers to the implementing type.…

SyntaxBest Practices
Open snippet →
Rust · Intermediate

Result<T, E> for Recoverable Errors

Result<T, E> represents recoverable errors: Ok(T) for success, Err(E) for failure. The ? operator propagates errors early, returning from the function immediately on Err. This is idiomatic Rust err…

Error HandlingBest Practices
Open snippet →
Rust · Intermediate

Understanding Lifetimes in Rust

Lifetimes are Rust's way of ensuring memory safety without garbage collection. They track how long references are valid. The 'a lifetime annotation connects the input and output references, guarant…

Memory ManagementSyntax
Open snippet →
Rust · Intermediate

Trait Bounds and Generic Constraints

Trait bounds constrain generic types to only accept values that implement certain behaviors. You can combine multiple bounds with +. The impl Trait syntax provides a shorter way to specify constrai…

GenericsSyntax
Open snippet →
Rust · Intermediate

Closures: Capturing Environment Variables

Closures can capture variables from their surrounding environment. Rust determines the capture mode automatically based on how the closure uses the variable: by reference, by mutable reference, or…

FunctionsMemory Management
Open snippet →
Rust · Intermediate

Slices: Working with Portions of Data

Slices let you reference a contiguous sequence of elements within a collection without taking ownership. The slice type is written as &[T] for an array or &str for string slices. String slices are…

Data TypesFunctions
Open snippet →
Rust · Intermediate

Interior Mutability with Cell Types

Cell types enable mutable data sharing in single-threaded scenarios where borrowing rules would normally prevent it. Cell<T> works with Copy types only, providing set and get methods. RefCell<T> wr…

Memory ManagementData Types
Open snippet →
Rust · Intermediate

Associated Types in Traits

Associated types allow you to define placeholder types within a trait that implementing types must specify. Unlike generic type parameters, associated types enforce a single concrete type per imple…

SyntaxBest Practices
Open snippet →
Rust · Intermediate

Panic Recovery and unwrap Variations

Rust provides graduated error handling strategies. catch_unwind captures panics for graceful recovery. expect provides clear error messages for Option/Result. unwrap_or offers fallback values. get…

Error HandlingBest Practices
Open snippet →
Rust · Intermediate

Newtype Pattern: Type-Safe Unit Wrappers

The newtype pattern wraps primitive types in tuple structs to create distinct types at zero runtime cost. This provides compile-time unit checking—Rust will refuse to pass Kilograms where Meters ar…

Data TypesBest Practices
Open snippet →
Rust · Intermediate

Lazy Initialization with OnceLock

OnceLock provides thread-safe lazy initialization for static data. The configuration is only read from disk when first accessed, not at program startup. This improves startup time if the config is…

Memory ManagementPerformance
Open snippet →
Rust · Intermediate

Unsafe Raw Pointers and MaybeUninit

Unsafe Rust grants direct memory access beyond what safe Rust permits. Raw pointers (*const T, *mut T) can be dereferenced only in unsafe blocks, acknowledging undefined behavior risks. MaybeUninit…

Memory ManagementUnsafe
Open snippet →
Rust · Intermediate

Pattern Matching with Match Expressions

Match expressions in Rust provide powerful pattern matching capabilities. You can match on enum variants, include guard clauses with 'if' conditions, and destructure complex data directly within th…

SyntaxData TypesControl Flow
Open snippet →
Rust · Intermediate

Iterator Adaptors and Lazy Evaluation

Rust iterators use lazy evaluation, meaning operations are not executed until consumed by a terminal operation like 'collect', 'sum', or 'for_each'. This allows chaining multiple adaptors like filt…

Arrays & ListsFunctionsPerformance
Open snippet →
Rust · Intermediate

Box<T> for Heap Allocation and Smart Pointers

Box<T> allocates values on the heap instead of the stack. It's the primary way to create singly-linked data structures like trees and linked lists in Rust. Box<T> implements the Deref trait, so you…

Memory ManagementData TypesBest Practices
Open snippet →