m12-lifecycle
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseResource Lifecycle
资源生命周期
Layer 2: Design Choices
第2层:设计选择
Core Question
核心问题
When should this resource be created, used, and cleaned up?
Before implementing lifecycle:
- What's the resource's scope?
- Who owns the cleanup responsibility?
- What happens on error?
应在何时创建、使用和清理该资源?
在实现生命周期之前:
- 资源的作用域是什么?
- 谁负责清理工作?
- 发生错误时会怎样?
Lifecycle Pattern → Implementation
生命周期模式 → 实现
| Pattern | When | Implementation |
|---|---|---|
| RAII | Auto cleanup | |
| Lazy init | Deferred creation | |
| Pool | Reuse expensive resources | |
| Guard | Scoped access | |
| Scope | Transaction boundary | Custom struct + Drop |
| 模式 | 适用场景 | 实现方式 |
|---|---|---|
| RAII | 自动清理 | |
| 惰性初始化 | 延迟创建 | |
| 连接池 | 复用昂贵资源 | |
| 守卫模式 | 作用域内访问 | |
| 作用域 | 事务边界 | 自定义结构体 + Drop |
Thinking Prompt
思考提示
Before designing lifecycle:
-
What's the resource cost?
- Cheap → create per use
- Expensive → pool or cache
- Global → lazy singleton
-
What's the scope?
- Function-local → stack allocation
- Request-scoped → passed or extracted
- Application-wide → static or Arc
-
What about errors?
- Cleanup must happen → Drop
- Cleanup is optional → explicit close
- Cleanup can fail → Result from close
在设计生命周期之前:
-
资源的成本如何?
- 低成本 → 每次使用时创建
- 高成本 → 使用连接池或缓存
- 全局资源 → 惰性单例
-
资源的作用域是什么?
- 函数局部 → 栈分配
- 请求作用域 → 传递或提取
- 应用全局 → 静态变量或Arc
-
错误处理如何应对?
- 必须执行清理 → 使用Drop
- 清理可选 → 显式关闭
- 清理可能失败 → 从close返回Result
Trace Up ↑
向上追溯 ↑
To domain constraints (Layer 3):
"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? |
到领域约束(第3层):
"我应该如何管理数据库连接?"
↑ 提问:连接的成本是多少?
↑ 检查:domain-*(延迟要求)
↑ 检查:基础设施(连接限制)| 问题 | 追溯至 | 提问 |
|---|---|---|
| 连接池 | domain-* | 可接受的延迟是多少? |
| 资源限制 | domain-* | 基础设施有哪些约束? |
| 事务作用域 | domain-* | 哪些操作必须是原子的? |
Trace Down ↓
向下追溯 ↓
To implementation (Layer 1):
"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到实现层(第1层):
"需要自动清理"
↓ m02-resource:实现Drop
↓ m01-ownership:明确清理的所有者
"需要惰性初始化"
↓ m03-mutability:使用OnceLock实现线程安全
↓ m07-concurrency:使用LazyLock实现同步
"需要连接池"
↓ m07-concurrency:线程安全的连接池
↓ m02-resource:使用Arc实现共享Quick Reference
快速参考
| 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 |
| 模式 | 类型 | 使用场景 |
|---|---|---|
| RAII | | 作用域退出时自动清理 |
| 惰性初始化 | | 延迟初始化 |
| 连接池 | | 连接复用 |
| 守卫模式 | | 作用域内锁释放 |
| 作用域 | 自定义结构体 | 事务边界 |
Lifecycle Events
生命周期事件
| Event | Rust Mechanism |
|---|---|
| Creation | |
| Lazy Init | |
| Usage | |
| Cleanup | |
| 事件 | Rust 机制 |
|---|---|
| 创建 | |
| 惰性初始化 | |
| 使用 | |
| 清理 | |
Pattern Templates
模式模板
RAII Guard
RAII 守卫
rust
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);
}
}rust
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);
}
}Lazy Singleton
惰性单例
rust
use std::sync::OnceLock;
static CONFIG: OnceLock<Config> = OnceLock::new();
fn get_config() -> &'static Config {
CONFIG.get_or_init(|| {
Config::load().expect("config required")
})
}rust
use std::sync::OnceLock;
static CONFIG: OnceLock<Config> = OnceLock::new();
fn get_config() -> &'static Config {
CONFIG.get_or_init(|| {
Config::load().expect("config required")
})
}Common Errors
常见错误
| 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 |
| 错误 | 原因 | 修复方案 |
|---|---|---|
| 资源泄漏 | 忘记实现Drop | 实现Drop或使用RAII包装器 |
| 双重释放 | 手动管理内存 | 交由Rust处理 |
| 悬垂引用 | 使用已释放的资源 | 检查生命周期 |
| E0509 从Drop中移出 | 移出拥有的字段 | 使用 |
| 连接池耗尽 | 未归还连接 | 确保Drop会归还连接 |
Anti-Patterns
反模式
| 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 |
| 反模式 | 弊端 | 更佳方案 |
|---|---|---|
| 手动清理 | 容易遗忘 | RAII/Drop |
| 依赖外部库 | |
| 全局可变状态 | 线程不安全 | |
| 忘记关闭 | 资源泄漏 | 实现Drop |
Related Skills
相关技能
| When | See |
|---|---|
| Smart pointers | m02-resource |
| Thread-safe init | m07-concurrency |
| Domain scopes | m09-domain |
| Error in cleanup | m06-error-handling |
| 场景 | 参考 |
|---|---|
| 智能指针 | m02-resource |
| 线程安全初始化 | m07-concurrency |
| 领域作用域 | m09-domain |
| 清理中的错误处理 | m06-error-handling |