Rust logoRust ADVANCED

Rust

Rust cheat sheet covering ownership, borrowing, lifetimes, pattern matching, traits, async/await, and systems programming examples.

12 min read
rustsystemsmemory-safetyconcurrencyperformance

Getting Started

Installation, setup, and basics

Installation & Setup

Install Rust and create your first project

bash
💡 Rustup manages Rust versions and toolchains
⚡ Cargo is Rust's build system and package manager
📌 Debug builds are fast to compile, release builds are optimized
🟢 Start with cargo new to create a project structure
installationsetupcargo

Hello World

Basic Rust program structure

rust
💡 fn main() is the entry point of every Rust program
⚡ println! is a macro, not a function (note the !)
📌 Rust macros can do compile-time code generation
🟢 String interpolation uses {} placeholders
basicshello-world

Variables & Types

Variable declarations, mutability, and basic types

Variables & Mutability

Declaring variables and understanding mutability

rust
💡 Variables are immutable by default for safety
⚡ Shadowing lets you reuse names with different types
📌 Constants are always immutable and require type annotation
🔐 Immutability prevents data races in concurrent code
variablesmutability

Basic Data Types

Scalar and compound types in Rust

rust
💡 Rust has signed (i) and unsigned (u) integers
⚡ Type inference is smart but explicit types add clarity
📌 char is 4 bytes and supports all Unicode
🟢 Arrays have fixed size, use Vec for dynamic arrays
typesdata-types

Ownership & Borrowing

Rust's unique ownership system for memory safety

Ownership Rules

Understanding Rust's ownership model

rust
💡 Each value has exactly one owner at a time
⚡ Move semantics prevent double-free errors
📌 Types with Copy trait are copied instead of moved
🔐 Ownership rules are enforced at compile time
ownershipmemory

Borrowing & References

Using references to avoid moving values

rust
💡 References allow borrowing without taking ownership
⚡ & for immutable reference, &mut for mutable
📌 Cannot have mutable and immutable refs simultaneously
🔐 Borrow checker prevents data races at compile time
borrowingreferences

Control Flow

Conditionals, loops, and pattern matching

If Expressions

Conditional branching in Rust

rust
💡 if is an expression, not a statement
⚡ Can use if in let bindings to assign values
📌 All branches must return the same type
🟢 No parentheses needed around conditions
control-flowconditionals

Loops

Different types of loops in Rust

rust
💡 loop creates infinite loops with explicit break
⚡ Loops can return values with break expression
📌 for loops are preferred for iterating collections
🟢 Use .iter() to borrow array elements in loops
loopsiteration

Pattern Matching

Powerful pattern matching with match

rust
💡 match must be exhaustive (cover all cases)
⚡ Use _ as catch-all pattern
📌 if let is syntactic sugar for single pattern
🎯 Match guards add extra conditions with if
pattern-matchingmatch

Functions & Closures

Function definitions, parameters, and closures

Function Basics

Defining and calling functions

rust
💡 Functions use snake_case naming convention
⚡ Last expression without semicolon is returned
📌 Parameters require type annotations
🟢 Use return for early returns, omit for final expression
functionsparameters

Closures

Anonymous functions with environment capture

rust
💡 Closures can capture variables from their environment
⚡ Type inference works for closure parameters
📌 Use move to take ownership of captured values
🎯 Closures are commonly used with iterators
closureslambdas

Structs & Enums

Custom data types and algebraic data types

Structs

Creating custom data types with structs

rust
💡 Structs group related data together
⚡ Use .. syntax to copy fields from another struct
📌 Field init shorthand when variable matches field name
🟢 Tuple structs useful for simple data without field names
structstypes

Enums

Algebraic data types with enums

rust
💡 Enums can hold different types of data in variants
⚡ Option<T> eliminates null pointer errors
📌 Result<T, E> for error handling
🎯 Match expressions work perfectly with enums
enumstypes

Methods & Impl Blocks

Adding methods to structs and enums

rust
💡 impl blocks define methods and associated functions
⚡ &self for immutable reference, &mut self for mutable
📌 Associated functions called with :: syntax
🟢 Multiple impl blocks allowed for organization
methodsimpl

Traits

Defining shared behavior with traits

Defining & Implementing Traits

Create traits, implement them, and use trait bounds

rust
🎯 Traits are Rust's way of defining shared behavior (like interfaces)
💡 impl Trait in params is sugar for generics — use where for complex bounds
📌 Default methods can be overridden by implementors
⚡ Return impl Trait hides concrete type — great for closures and iterators

Common Traits & Derive

Standard library traits and the derive macro

rust
📌 Debug, Clone, PartialEq are the most commonly derived traits
💡 Display provides user-facing output — also enables .to_string()
🎯 Implement From<T> and you get Into<T> for free
⚡ Copy is only for small stack-allocated types (integers, bools, tuples)

Generics

Generic types, functions, and constraints

Generic Functions & Types

Parameterize functions, structs, and enums over types

rust
🎯 Generics are zero-cost — monomorphized at compile time
💡 Use trait bounds to constrain what generic types can do
📌 impl<T> is generic impl, impl Point<f64> is type-specific impl
⚡ Option<T> and Result<T, E> are the most common generic types

Lifetimes

Lifetime annotations for references

Lifetime Annotations

Annotate lifetimes to help the borrow checker

rust
📌 Lifetimes prevent dangling references — they don't change how long data lives
💡 The compiler elides lifetimes in common cases (3 rules) — only annotate when needed
🎯 'a means "at least as long as" — the output lives as long as the shortest input
⚡ 'static means the reference lives for the entire program (string literals, leaked data)

Error Handling

Handling errors with Result and Option

Result Type

Error handling with Result<T, E>

rust
💡 Result<T, E> for recoverable errors
⚡ ? operator propagates errors up the call stack
📌 unwrap() panics on error, expect() with custom message
🔐 Compiler forces you to handle all errors
error-handlingresult

Option Type

Handling optional values with Option<T>

rust
💡 Option<T> represents optional values without null
⚡ Many useful methods: map, and_then, unwrap_or
📌 ? operator works with Option in functions returning Option
🟢 if let for simple pattern matching
optionnull-safety

Collections

Vectors, strings, and hash maps

Vectors

Dynamic arrays with Vec<T>

rust
💡 Vectors are resizable arrays stored on the heap
⚡ vec! macro for convenient initialization
📌 Use get() for safe access that returns Option
🟢 Vectors can only store values of the same type
vectorscollections

Strings

String manipulation and UTF-8 text

rust
💡 String is growable, heap-allocated, UTF-8
⚡ &str is an immutable reference to a string slice
📌 Cannot index strings due to UTF-8 encoding
🌍 Properly handles Unicode and international text
stringstext

Hash Maps

Key-value storage with HashMap

rust
💡 HashMap<K, V> stores key-value pairs
⚡ Keys must implement Eq and Hash traits
📌 entry() API for efficient conditional updates
🟢 Use BTreeMap for sorted keys
hashmapcollections

Iterators

Iterator adaptors and consuming methods

Iterator Methods

Chaining iterator adaptors and collectors

rust
🎯 Adaptors are lazy (filter, map, take) — consumers trigger execution (collect, sum, count)
💡 iter() borrows, iter_mut() mutably borrows, into_iter() takes ownership
📌 collect() needs a type hint — use turbofish ::<Vec<_>> or annotate the variable
⚡ Iterator chains are zero-cost — compiled to the same code as manual loops

Smart Pointers

Heap allocation and reference counting

Box, Rc & RefCell

Heap allocation, shared ownership, and interior mutability

rust
📌 Box<T> for heap allocation + recursive types + trait objects
💡 Rc<T> for shared ownership — Rc::clone is cheap (just bumps ref count)
⚠️ RefCell<T> moves borrow checking to runtime — panics on violation
⚡ For multithreaded code, use Arc<T> instead of Rc<T> and Mutex<T> instead of RefCell<T>

Concurrency

Threads, channels, and shared state

Threads & Channels

Spawn threads and communicate with message passing

rust
🎯 Use move to transfer ownership into spawned threads
📌 Arc<Mutex<T>> is the standard pattern for shared mutable state across threads
💡 thread::scope lets threads borrow from parent — no Arc needed
⚡ Channels are great for message passing — prefer over shared state when possible

Modules & Cargo

Code organization and package management

Modules & Visibility

Organize code with modules and control visibility

rust
📌 Items are private by default — use pub to expose them
🎯 mod loads from file.rs or file/mod.rs — one module per file
💡 pub(crate) makes items visible within the crate but not to dependents
⚡ use crate:: for absolute paths, use super:: for parent module

Cargo Essentials

Package management and project commands

📄 Codebash
🎯 cargo check is faster than cargo build — use it for quick type checking
📌 cargo clippy catches bugs and suggests idiomatic Rust patterns
💡 cargo add is the easiest way to manage dependencies (since Rust 1.62)
⚡ Use --release for benchmarks and production — debug builds are much slower

Testing

Unit tests, integration tests, and assertions

Writing Tests

Unit tests, assertions, and test organization

rust
📌 #[cfg(test)] ensures test code is not included in release builds
💡 assert!, assert_eq!, assert_ne! are the core assertion macros
🎯 Integration tests go in tests/ dir and can only test public API
⚡ cargo test runs unit + integration tests; use --lib for unit only