Files
poimen-memory/knowledge/rust-fundamentals.md
T
rock 762acea610
Build and Push / Test (push) Failing after 6s
Build and Push / Build and push image (push) Skipped
feat: add 'mem learn' CLI for markdown knowledge ingestion
6 knowledge files: rust, SOLID/DRY, ast-grep, karpathy, golang, caveman
65 chunks ingested to log/knowledge/learn/latest.jsonl
Chunks on ## headings, SHA256 dedup, configurable chunk size
2026-08-29 22:04:14 -07:00

64 lines
3.2 KiB
Markdown

# 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<T, E>` 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<T: Summary>(item: &T)`
- `dyn Trait` for trait objects (dynamic dispatch), `impl Trait` for static dispatch.
- Blanket implementations: `impl<T: Display> ToString for T`
## Smart Pointers
- `Box<T>` heap allocation with single ownership.
- `Rc<T>` reference-counted shared ownership (single-threaded).
- `Arc<T>` atomic reference-counted (thread-safe). Use with `Mutex<T>` or `RwLock<T>`.
- `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::<Vec<_>>()`
- `impl Iterator for MyType { type Item = T; fn next(&mut self) -> Option<Self::Item> }`
## 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<T>`, `RefCell<T>` for single-threaded, `Mutex<T>` for multi-threaded.