# Rust Fundamentals ## Ownership & Borrowing - Every value has exactly one owner. When owner goes out of scope, value is dropped. - `&T` immutable borrow, `&mut T` mutable borrow. Cannot have `&mut` while `&` exists. - Move semantics by default for non-Copy types. Clone for explicit deep copy. ## Lifetimes - `'a` annotations tell compiler how long references live. - Elision rules: single input lifetime → applied to all outputs. `&self` → output gets `'self` lifetime. - `'static` means reference lives for entire program. String literals are `&'static str`. ## Error Handling - `Result` for recoverable errors, `panic!` for unrecoverable. - `?` operator propagates errors. Use `anyhow::Result` for application code, `thiserror` for library errors. - Never use `.unwrap()` in production — use `.expect("reason")` or proper error handling. ## Traits & Generics - Traits define shared behavior: `trait Summary { fn summarize(&self) -> String; }` - Trait bounds: `fn notify(item: &impl Summary)` or `fn notify(item: &T)` - `dyn Trait` for trait objects (dynamic dispatch), `impl Trait` for static dispatch. - Blanket implementations: `impl ToString for T` ## Smart Pointers - `Box` heap allocation with single ownership. - `Rc` reference-counted shared ownership (single-threaded). - `Arc` atomic reference-counted (thread-safe). Use with `Mutex` or `RwLock`. - `Cow<'a, T>` clone-on-write — borrows when possible, clones when mutation needed. ## Concurrency - `Send` — type can be transferred across threads. `Sync` — type can be shared between threads. - `tokio::spawn` for async tasks. `rayon` for data parallelism. - Channels: `mpsc::channel()` for multi-producer single-consumer. `crossbeam` for advanced patterns. - `async/await` — futures are lazy, must be `.await`ed or spawned. ## Pattern Matching - `match` is exhaustive — must cover all variants. - `if let Some(x) = option` for single-pattern matching. - Destructuring: `let (a, b) = tuple;` and `let Point { x, y } = point;` - Guards: `match x { n if n > 0 => ..., _ => ... }` ## Module System - `mod foo;` loads from `foo.rs` or `foo/mod.rs`. - `pub(crate)` visible within crate only. `pub(super)` visible to parent module. - `use crate::module::Type` absolute path. `use super::Type` relative path. - Re-exports: `pub use inner::Type;` to flatten module hierarchy. ## Iterators - `.iter()` borrows, `.into_iter()` consumes, `.iter_mut()` mutable borrow. - Lazy — nothing happens until consumed (`.collect()`, `.for_each()`, `.count()`). - Chaining: `.filter().map().flat_map().take().collect::>()` - `impl Iterator for MyType { type Item = T; fn next(&mut self) -> Option }` ## Macros - `macro_rules!` for declarative macros. `#[derive(...)]` for derive macros. - `proc_macro` for procedural macros (attribute, derive, function-like). - `vec![1, 2, 3]` expands to `{ let mut v = Vec::new(); v.push(1); ... v }` ## Common Patterns - Builder pattern: `MyStruct::new().with_field(val).build()` - Newtype pattern: `struct UserId(u64);` for type safety without runtime cost. - Type state pattern: use generics to encode state in the type system. - Interior mutability: `Cell`, `RefCell` for single-threaded, `Mutex` for multi-threaded.