m12-lifecycle

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Resource 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

生命周期模式 → 实现

PatternWhenImplementation
RAIIAuto cleanup
Drop
trait
Lazy initDeferred creation
OnceLock
,
LazyLock
PoolReuse expensive resources
r2d2
,
deadpool
GuardScoped access
MutexGuard
pattern
ScopeTransaction boundaryCustom struct + Drop

模式适用场景实现方式
RAII自动清理
Drop
trait
惰性初始化延迟创建
OnceLock
,
LazyLock
连接池复用昂贵资源
r2d2
,
deadpool
守卫模式作用域内访问
MutexGuard
模式
作用域事务边界自定义结构体 + Drop

Thinking Prompt

思考提示

Before designing lifecycle:
  1. What's the resource cost?
    • Cheap → create per use
    • Expensive → pool or cache
    • Global → lazy singleton
  2. What's the scope?
    • Function-local → stack allocation
    • Request-scoped → passed or extracted
    • Application-wide → static or Arc
  3. What about errors?
    • Cleanup must happen → Drop
    • Cleanup is optional → explicit close
    • Cleanup can fail → Result from close

在设计生命周期之前:
  1. 资源的成本如何?
    • 低成本 → 每次使用时创建
    • 高成本 → 使用连接池或缓存
    • 全局资源 → 惰性单例
  2. 资源的作用域是什么?
    • 函数局部 → 栈分配
    • 请求作用域 → 传递或提取
    • 应用全局 → 静态变量或Arc
  3. 错误处理如何应对?
    • 必须执行清理 → 使用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)
QuestionTrace ToAsk
Connection poolingdomain-*What's acceptable latency?
Resource limitsdomain-*What are infra constraints?
Transaction scopedomain-*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

快速参考

PatternTypeUse Case
RAII
Drop
trait
Auto cleanup on scope exit
Lazy Init
OnceLock
,
LazyLock
Deferred initialization
Pool
r2d2
,
deadpool
Connection reuse
Guard
MutexGuard
Scoped lock release
ScopeCustom structTransaction boundaries
模式类型使用场景
RAII
Drop
trait
作用域退出时自动清理
惰性初始化
OnceLock
,
LazyLock
延迟初始化
连接池
r2d2
,
deadpool
连接复用
守卫模式
MutexGuard
作用域内锁释放
作用域自定义结构体事务边界

Lifecycle Events

生命周期事件

EventRust Mechanism
Creation
new()
,
Default
Lazy Init
OnceLock::get_or_init
Usage
&self
,
&mut self
Cleanup
Drop::drop()
事件Rust 机制
创建
new()
,
Default
惰性初始化
OnceLock::get_or_init
使用
&self
,
&mut self
清理
Drop::drop()

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

常见错误

ErrorCauseFix
Resource leakForgot DropImplement Drop or RAII wrapper
Double freeManual memoryLet Rust handle
Use after dropDangling referenceCheck lifetimes
E0509 move out of DropMoving owned field
Option::take()
Pool exhaustionNot returnedEnsure Drop returns

错误原因修复方案
资源泄漏忘记实现Drop实现Drop或使用RAII包装器
双重释放手动管理内存交由Rust处理
悬垂引用使用已释放的资源检查生命周期
E0509 从Drop中移出移出拥有的字段使用
Option::take()
连接池耗尽未归还连接确保Drop会归还连接

Anti-Patterns

反模式

Anti-PatternWhy BadBetter
Manual cleanupEasy to forgetRAII/Drop
lazy_static!
External dep
std::sync::OnceLock
Global mutable stateThread unsafety
OnceLock
or proper sync
Forget to closeResource leakDrop impl

反模式弊端更佳方案
手动清理容易遗忘RAII/Drop
lazy_static!
依赖外部库
std::sync::OnceLock
全局可变状态线程不安全
OnceLock
或适当的同步机制
忘记关闭资源泄漏实现Drop

Related Skills

相关技能

WhenSee
Smart pointersm02-resource
Thread-safe initm07-concurrency
Domain scopesm09-domain
Error in cleanupm06-error-handling
场景参考
智能指针m02-resource
线程安全初始化m07-concurrency
领域作用域m09-domain
清理中的错误处理m06-error-handling