m01-ownership

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Ownership & Lifetimes

Ownership & Lifetimes

Layer 1: Language Mechanics
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?

错误码不要只说应转而提问
E0382“克隆它”谁应该拥有这份数据?
E0597“延长生命周期”作用域边界是否合理?
E0506“先结束借用”变更操作是否应该在其他位置进行?
E0507“转移前先克隆”为什么要从引用中转移值?
E0515“返回拥有权”调用者是否应该拥有这份数据?
E0716“绑定到变量”为什么这是临时值?
E0106“添加'a”实际的生命周期关系是什么?

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

在修复所有权错误之前,请先思考:
  1. 这份数据在业务领域中的角色是什么?
    • 实体(唯一标识)→ 拥有所有权
    • 值对象(可互换)→ 允许克隆/复制
    • 临时值(计算结果)→ 可能需要重构代码
  2. 当前的所有权设计是有意为之吗?
    • 有意设计 → 在约束范围内解决问题
    • 意外产生 → 考虑重新设计
  3. 修复表面问题还是重新设计?
    • 如果是第三次尝试仍未解决 → 升级到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?

当错误持续存在时,追溯到设计层面:
E0382 (moved value)
    ↑ 提问:是什么设计选择导致了这种所有权模式?
    ↑ 检查:m09-domain(这是实体还是值对象?)
    ↑ 检查:domain-*(有哪些约束条件?)
持续出现的错误追溯至问题
E0382重复出现m02-resource是否应该使用Arc/Rc进行共享?
E0597重复出现m09-domain作用域边界是否设置在正确位置?
E0506/E0507m03-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)

从设计决策到具体实现:
“数据需要被不可变共享”
    ↓ 使用:Arc<T>(多线程)或Rc<T>(单线程)

“数据需要独占所有权”
    ↓ 使用:move语义,获取所有权

“数据是只读视图”
    ↓ 使用:&T(不可变借用)

Quick Reference

快速参考

PatternOwnershipCostUse When
MoveTransferZeroCaller doesn't need data
&T
BorrowZeroRead-only access
&mut T
Exclusive 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
模式所有权特性成本使用场景
Move转移所有权零成本调用者不再需要该数据
&T
借用零成本只读访问
&mut T
独占借用零成本需要修改数据
clone()
复制数据内存分配+复制确实需要一份副本
Rc<T>
共享所有权(单线程)引用计数单线程环境下共享数据
Arc<T>
共享所有权(多线程)原子引用计数多线程环境下共享数据
Cow<T>
写时复制仅在修改时分配内存可能会修改数据

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

错误码原因快速修复方案
E0382值已转移克隆、引用或重新设计所有权
E0597引用的生命周期超过所有者延长所有者作用域或重构代码
E0506借用期间进行赋值先结束借用再执行变更操作
E0507从借用中转移值克隆或使用引用
E0515返回局部变量的引用返回拥有所有权的值
E0716临时值已被销毁绑定到变量
E0106缺少生命周期标注添加
'a
标注

Anti-Patterns

反模式

Anti-PatternWhy BadBetter
.clone()
everywhere
Hides design issuesDesign ownership properly
Fight borrow checkerIncreases complexityWork with the compiler
'static
for everything
Restricts flexibilityUse appropriate lifetimes
Leak with
Box::leak
Memory leakProper lifetime design

反模式问题所在更佳方案
到处使用
.clone()
隐藏设计问题合理设计所有权
对抗借用检查器增加复杂度配合编译器解决问题
所有场景都用
'static
限制灵活性使用合适的生命周期
Box::leak
泄漏内存
内存泄漏合理设计生命周期

Related Skills

相关技能

WhenSee
Need smart pointersm02-resource
Need interior mutabilitym03-mutability
Data is domain entitym09-domain
Learning ownership conceptsm14-mental-model
场景参考内容
需要使用智能指针m02-resource
需要使用内部可变性m03-mutability
数据是领域实体m09-domain
学习所有权概念m14-mental-model