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 從公開儲存庫中收錄這些內容。

檢舉或申請下架