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
3.2 KiB
3.2 KiB
Rust Fundamentals
Ownership & Borrowing
- Every value has exactly one owner. When owner goes out of scope, value is dropped.
&Timmutable borrow,&mut Tmutable borrow. Cannot have&mutwhile&exists.- Move semantics by default for non-Copy types. Clone for explicit deep copy.
Lifetimes
'aannotations tell compiler how long references live.- Elision rules: single input lifetime → applied to all outputs.
&self→ output gets'selflifetime. 'staticmeans reference lives for entire program. String literals are&'static str.
Error Handling
Result<T, E>for recoverable errors,panic!for unrecoverable.?operator propagates errors. Useanyhow::Resultfor application code,thiserrorfor 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)orfn notify<T: Summary>(item: &T) dyn Traitfor trait objects (dynamic dispatch),impl Traitfor 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 withMutex<T>orRwLock<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::spawnfor async tasks.rayonfor data parallelism.- Channels:
mpsc::channel()for multi-producer single-consumer.crossbeamfor advanced patterns. async/await— futures are lazy, must be.awaited or spawned.
Pattern Matching
matchis exhaustive — must cover all variants.if let Some(x) = optionfor single-pattern matching.- Destructuring:
let (a, b) = tuple;andlet Point { x, y } = point; - Guards:
match x { n if n > 0 => ..., _ => ... }
Module System
mod foo;loads fromfoo.rsorfoo/mod.rs.pub(crate)visible within crate only.pub(super)visible to parent module.use crate::module::Typeabsolute path.use super::Typerelative 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_macrofor 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.