M01 Ownership

作者 actionbook5c40d3ad7851無授權條款1.5K 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫6 週前更新

CRITICAL: Use for ownership/borrow/lifetime issues. Triggers: E0382, E0597, E0506, E0507, E0515, E0716, E0106, value moved, borrowed value does not live long enough, cannot move out of, use of moved value, ownership, borrow, lifetime, 'a, 'static, move, clone, Copy, 所有权, 借用, 生命周期

AI 產生的概覽

引導分析 Rust 所有權、借用與生命週期錯誤,將編譯器錯誤碼對應到設計問題。

功能
此技能提供一套結構化思路,用來處理 Rust 的所有權、借用與生命週期問題,而不是直接套用快速修正。它把 E0382、E0597、E0506、E0507、E0515、E0716、E0106 等常見編譯器錯誤,對應到關於資料該由誰擁有、存活多久的設計問題。它也包含所有權模式、錯誤成因與反模式的速查表,並說明何時該上溯到設計層、何時該下推到實作選擇。
適用情境
當 Rust 程式因所有權、借用或生命週期錯誤而無法編譯時使用,例如值被移動、借用值的存活時間不夠長,或缺少生命週期標註。在決定某筆資料該用 move、借用、clone、Rc、Arc 還是 Cow 時也適用。
執行需求
不需要指令碼或特殊工具,僅為純說明性參考文件。使用者需熟悉 Rust 及其編譯器錯誤碼。

Ownership & Lifetimes

Layer 1: Language Mechanics

Core Question

Who should own this data, and for how long?

Before fixing ownership errors, understand the data's role:

  • Is it shared or exclusive?
  • Is it short-lived or long-lived?
  • Is it transformed or just read?

Error → Design Question

ErrorDon't Just SayAsk Instead
E0382"Clone it"Who should own this data?
E0597"Extend lifetime"Is the scope boundary correct?
E0506"End borrow first"Should mutation happen elsewhere?
E0507"Clone before move"Why are we moving from a reference?
E0515"Return owned"Should caller own the data?
E0716"Bind to variable"Why is this temporary?
E0106"Add 'a"What is the actual lifetime relationship?

Thinking Prompt

Before fixing an ownership error, ask:

  1. What is this data's domain role?

    • Entity (unique identity) → owned
    • Value Object (interchangeable) → clone/copy OK
    • Temporary (computation result) → maybe restructure
  2. Is the ownership design intentional?

    • By design → work within constraints
    • Accidental → consider redesign
  3. Fix symptom or redesign?

    • If Strike 3 (3rd attempt) → escalate to Layer 2

Trace Up ↑

When errors persist, trace to design layer:

E0382 (moved value)    ↑ Ask: What design choice led to this ownership pattern?    ↑ Check: m09-domain (is this Entity or Value Object?)    ↑ Check: domain-* (what constraints apply?)
Persistent ErrorTrace ToQuestion
E0382 repeatedm02-resourceShould use Arc/Rc for sharing?
E0597 repeatedm09-domainIs scope boundary at right place?
E0506/E0507m03-mutabilityShould use interior mutability?

Trace Down ↓

From design decisions to implementation:

"Data needs to be shared immutably"    ↓ Use: Arc<T> (multi-thread) or Rc<T> (single-thread)
"Data needs exclusive ownership"    ↓ Use: move semantics, take ownership
"Data is read-only view"    ↓ Use: &T (immutable borrow)

Quick Reference

PatternOwnershipCostUse When
MoveTransferZeroCaller doesn't need data
&TBorrowZeroRead-only access
&mut TExclusive borrowZeroNeed to modify
clone()DuplicateAlloc + copyActually need a copy
Rc<T>Shared (single)Ref countSingle-thread sharing
Arc<T>Shared (multi)Atomic ref countMulti-thread sharing
Cow<T>Clone-on-writeAlloc if mutatedMight modify

Error Code Reference

ErrorCauseQuick Fix
E0382Value movedClone, reference, or redesign ownership
E0597Reference outlives ownerExtend owner scope or restructure
E0506Assign while borrowedEnd borrow before mutation
E0507Move out of borrowedClone or use reference
E0515Return local referenceReturn owned value
E0716Temporary droppedBind to variable
E0106Missing lifetimeAdd 'a annotation

Anti-Patterns

Anti-PatternWhy BadBetter
.clone() everywhereHides design issuesDesign ownership properly
Fight borrow checkerIncreases complexityWork with the compiler
'static for everythingRestricts flexibilityUse appropriate lifetimes
Leak with Box::leakMemory leakProper lifetime design

Related Skills

WhenSee
Need smart pointersm02-resource
Need interior mutabilitym03-mutability
Data is domain entitym09-domain
Learning ownership conceptsm14-mental-model

來源與署名

來源:actionbook/rust-skills位於skills/m01-ownership提交5c40d3a

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架