STACK HEAP

🦀 Rust

Ownership, lifetimes, traits, async

Ownership Rules

1

Each value has exactly one owner

let s1 = String::from("hello"); // s1 owns it
2

When the owner goes out of scope, value is dropped

{ let s = String::from("hi"); } // dropped here
3

Assignment moves ownership (no copy for heap data)

let s2 = s1; // s1 is now invalid
4

Clone for explicit deep copy

let s2 = s1.clone(); // both valid
5

Copy trait for stack-only data (i32, bool, f64, char)

let x = 5; let y = x; // both valid (Copy)

Borrowing Rules

Immutable borrow: &T

Multiple readers allowed

fn len(s: &String) -> usize
Mutable borrow: &mut T

Exclusive writer (only 1)

fn push(s: &mut String)
Can't mix &T and &mut T

No aliasing + mutation

// compiler rejects this
References must outlive their use

Dangling ref = compile error

// lifetime annotations 'a

Lifetimes

&'a str Reference valid for lifetime 'a
'static Lives for entire program (string literals, leaked)
fn foo<'a>(x: &'a str) -> &'a str Output lives as long as input
struct Foo<'a> { s: &'a str } Struct can't outlive the reference
Elision rules Compiler infers lifetimes in common patterns (1-input → output)

Key Traits

Display

User-facing formatting (println!("{}"))

Debug

Developer formatting (println!("{:?}"))

Clone / Copy

Clone: explicit dup. Copy: implicit (stack-only).

From / Into

Type conversion. impl From<T> gets Into<U> free

Iterator

fn next(&mut self) -> Option<Item>. Lazy + composable

Deref / DerefMut

Smart pointer dereferencing. &Box<T> → &T

Drop

Destructor. Called when value goes out of scope

Send / Sync

Send: safe to transfer across threads. Sync: safe to share refs

Fn / FnMut / FnOnce

Closure traits. Capture by ref / mut ref / value

Error Handling

Result<T, E> Ok(T) or Err(E). Use ? operator for propagation
Option<T> Some(T) or None. Use ? in functions returning Option
unwrap() / expect() Panic on None/Err. Only in tests or when guaranteed
map / and_then / unwrap_or Combinators for chaining operations
anyhow::Result Catch-all error type for applications
thiserror Derive macro for custom error types in libraries

Smart Pointers

Box<T>

Heap allocation. Single owner. Recursive types.

Rc<T>

Reference counting. Multiple owners (single-threaded).

Arc<T>

Atomic Rc. Multiple owners (thread-safe).

RefCell<T>

Interior mutability. Runtime borrow checking.

Mutex<T>

Thread-safe interior mutability. Lock before access.

RwLock<T>

Many readers OR one writer (thread-safe).

Async Rust

async fn Returns impl Future<Output = T>. Lazy (does nothing until .await)
.await Suspends until future completes. Must be in async context
tokio Most popular runtime. tokio::spawn for tasks, tokio::select! for racing
Pin<Box<Future>> Required for self-referential futures. Usually hidden by async/await
Stream Async iterator. .next().await returns Option<Item>