Smart Pointers: Beyond Single Ownership
智能指针:超越单一所有权
What you’ll learn: When
Box,Rc,Arc,RefCell, andMutexare needed, and how they compare to Java’s always-reference-based object model.
本章将学习: 什么时候该用Box、Rc、Arc、RefCell、Mutex,以及它们和 Java 那种“对象默认全靠引用”模型有什么区别。Difficulty: 🔴 Advanced
难度: 🔴 高级
Java developers are used to object references everywhere. Rust starts from direct ownership and only adds pointer-like wrappers when they are actually needed.
Java 开发者习惯了对象到处都是引用。Rust 则是先从直接所有权开始,只有真的需要时才引入带指针味道的包装类型。
Common Smart Pointers
常见智能指针
| Type | Typical use |
|---|---|
Box<T> | heap allocation with single ownership 单一所有权下的堆分配 |
Rc<T> | shared ownership in single-threaded code 单线程共享所有权 |
Arc<T> | shared ownership across threads 跨线程共享所有权 |
RefCell<T> | checked interior mutability in single-threaded code 单线程内部可变性 |
Mutex<T> | synchronized shared mutable access 同步共享可变访问 |
The Key Difference from Java
和 Java 的关键差异
In Java, shared references are the default. In Rust, shared ownership is a deliberate choice with a specific type.
在 Java 里,共享引用是默认状态;在 Rust 里,共享所有权必须通过专门类型显式表达。
Guidance
使用建议
- use plain values and references first
优先从普通值和引用开始。 - add
Boxwhen recursive or heap-allocated layout is needed
递归结构或需要稳定堆布局时,再加Box。 - add
RcorArconly when multiple owners are truly required
只有真的存在多个 owner 时,再上Rc或Arc。 - pair
ArcwithMutexonly when shared mutable state is unavoidable
只有共享可变状态躲不过去时,才把Arc和Mutex配一起。
These types are powerful, but they are also signals that the ownership model has become more complex.
这些类型很好用,但它们同时也是信号:代码里的所有权关系已经开始变复杂了。