M12 Lifecycle

作者 actionbook5c40d3ad7851无许可证1.5K 个星标收录于 2026年10月8日更新于 2026年10月8日仓库6周前更新

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 模式

AI 生成的概览

指导 Rust 资源生命周期设计,涵盖 RAII、惰性初始化、连接池、守卫与清理。

功能
该技能提供一套设计框架,用于判断资源应在何时创建、使用和清理。它把 RAII、惰性初始化、池化、守卫和事务作用域等生命周期模式对应到 Drop、OnceLock、LazyLock、r2d2 和 deadpool 等 Rust 机制。内容还包括生命周期事件、模式模板、常见错误与反模式,并指向所有权、并发、领域作用域和错误处理等相关技能。
适用场景
适合在设计资源的创建、共享和释放方式时使用,例如连接池、惰性单例、作用域守卫或事务边界。也适用于确定清理责任以及清理出错时的处理方式。
运行要求
无需脚本或工具,仅为纯说明性参考。示例假定使用 Rust,并提到 r2d2、deadpool 等 crate,但阅读这些指导不需要安装任何东西。

Resource Lifecycle

Layer 2: Design Choices

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 cleanupDrop trait
Lazy initDeferred creationOnceLock, LazyLock
PoolReuse expensive resourcesr2d2, deadpool
GuardScoped accessMutexGuard pattern
ScopeTransaction boundaryCustom struct + 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

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?

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

Quick Reference

PatternTypeUse Case
RAIIDrop traitAuto cleanup on scope exit
Lazy InitOnceLock, LazyLockDeferred initialization
Poolr2d2, deadpoolConnection reuse
GuardMutexGuardScoped lock release
ScopeCustom structTransaction boundaries

Lifecycle Events

EventRust Mechanism
Creationnew(), Default
Lazy InitOnceLock::get_or_init
Usage&self, &mut self
CleanupDrop::drop()

Pattern Templates

RAII Guard

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")    })}

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 fieldOption::take()
Pool exhaustionNot returnedEnsure Drop returns

Anti-Patterns

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

Related Skills

WhenSee
Smart pointersm02-resource
Thread-safe initm07-concurrency
Domain scopesm09-domain
Error in cleanupm06-error-handling

来源与署名

来源:actionbook/rust-skills位于skills/m12-lifecycle提交5c40d3a

许可证: 无许可证

内容归原作者所有。SourceWeft 从公开仓库中收录这些内容。

举报或申请下架