Loading...
Loading...
Use when designing resource lifecycles. Keywords: RAII, Drop, resource lifecycle, connection pool, lazy initialization, connection pool design, resource cleanup patterns, cleanup, scope, OnceCell, Lazy, once_cell, OnceLock, transaction, session management, when is Drop called, cleanup on error, guard pattern, scope guard, 资源生命周期, 连接池, 惰性初始化, 资源清理, RAII 模式
npx skill4agent add actionbook/rust-skills m12-lifecycleLayer 2: Design Choices
| Pattern | When | Implementation |
|---|---|---|
| RAII | Auto cleanup | |
| Lazy init | Deferred creation | |
| Pool | Reuse expensive resources | |
| Guard | Scoped access | |
| Scope | Transaction boundary | Custom struct + Drop |
"How should I manage database connections?"
↑ Ask: What's the connection cost?
↑ Check: domain-* (latency requirements)
↑ Check: Infrastructure (connection limits)| Question | Trace To | Ask |
|---|---|---|
| Connection pooling | domain-* | What's acceptable latency? |
| Resource limits | domain-* | What are infra constraints? |
| Transaction scope | domain-* | What must be atomic? |
"Need automatic cleanup"
↓ m02-resource: Implement Drop
↓ m01-ownership: Clear owner for cleanup
"Need lazy initialization"
↓ m03-mutability: OnceLock for thread-safe
↓ m07-concurrency: LazyLock for sync
"Need connection pool"
↓ m07-concurrency: Thread-safe pool
↓ m02-resource: Arc for sharing| Pattern | Type | Use Case |
|---|---|---|
| RAII | | Auto cleanup on scope exit |
| Lazy Init | | Deferred initialization |
| Pool | | Connection reuse |
| Guard | | Scoped lock release |
| Scope | Custom struct | Transaction boundaries |
| Event | Rust Mechanism |
|---|---|
| Creation | |
| Lazy Init | |
| Usage | |
| Cleanup | |
struct FileGuard {
path: PathBuf,
_handle: File,
}
impl Drop for FileGuard {
fn drop(&mut self) {
// Cleanup: remove temp file
let _ = std::fs::remove_file(&self.path);
}
}use std::sync::OnceLock;
static CONFIG: OnceLock<Config> = OnceLock::new();
fn get_config() -> &'static Config {
CONFIG.get_or_init(|| {
Config::load().expect("config required")
})
}| Error | Cause | Fix |
|---|---|---|
| Resource leak | Forgot Drop | Implement Drop or RAII wrapper |
| Double free | Manual memory | Let Rust handle |
| Use after drop | Dangling reference | Check lifetimes |
| E0509 move out of Drop | Moving owned field | |
| Pool exhaustion | Not returned | Ensure Drop returns |
| Anti-Pattern | Why Bad | Better |
|---|---|---|
| Manual cleanup | Easy to forget | RAII/Drop |
| External dep | |
| Global mutable state | Thread unsafety | |
| Forget to close | Resource leak | Drop impl |
| When | See |
|---|---|
| Smart pointers | m02-resource |
| Thread-safe init | m07-concurrency |
| Domain scopes | m09-domain |
| Error in cleanup | m06-error-handling |