- Home
- Skills
- Zhanghandong
- Rust Skills
- M02 Resource
m02-resource_skill
- Shell
565
GitHub Stars
1
Bundled Files
2 months ago
Catalog Refreshed
4 months ago
First Indexed
Readme & install
Copy the install command, review bundled files from the catalogue, and read any extended description pulled from the listing source.
Installation
Preview and clipboard use veilstrat where the catalogue uses aiagentskills.
npx veilstrat add skill zhanghandong/rust-skills --skill m02-resource- SKILL.md4.3 KB
Overview
This skill guides smart pointer and resource management decisions in Rust. It helps you pick between Box, Rc, Arc, Weak, Cell, and RefCell based on ownership, threading, and potential reference cycles. It focuses on practical trade-offs and common pitfalls to prevent leaks, panics, and unnecessary overhead.
How this skill works
The skill inspects the ownership model, thread context, and mutability needs to recommend appropriate smart pointers. It traces from high-level design questions (single vs shared ownership, single- vs multi-threaded) down to concrete types and compositions (e.g., Rc<RefCell<T>> vs Arc<Mutex<T>>). It highlights failure modes and suggests checks or alternatives when common errors appear.
When to use it
- Need heap allocation for a single owner or recursive type → consider Box<T>.
- Shared ownership on a single thread → use Rc<T>.
- Shared ownership across threads → use Arc<T>.
- Need to break cycles → introduce Weak<T> on one direction.
- Require interior mutability: single-thread → Cell/RefCell, multi-thread → Mutex/RwLock inside Arc.
Best practices
- Always identify the ownership model first: single owner, shared, or weak reference.
- Determine thread context early; default to Rc and RefCell for single-threaded code to avoid atomic overhead.
- Avoid using Arc everywhere—accept the cost only if true cross-thread sharing is required.
- Break potential cycles by converting one strong reference to Weak to prevent leaks.
- Prefer stack allocation and plain values until heap allocation is justified; don’t Box small types unnecessarily.
Example use cases
- Storing a recursive AST node: use Box<T> for child pointers to avoid infinite size.
- Shared configuration data accessed only on the main thread: use Rc<T> to share immutable data.
- Shared cache accessed by worker threads: use Arc<T> for safe cross-thread sharing.
- Parent-child graph where children hold references back to parent: use Weak<T> for the parent link to avoid cycles.
- Mutable shared state in a single-threaded GUI: use Rc<RefCell<T>> for interior mutability without locks.
FAQ
Pick Rc when data is shared only within one thread; Rc has no atomic overhead. Choose Arc when the data must be shared safely across threads.
How do I avoid RefCell panics at runtime?
Prefer static ownership where possible. If runtime borrow conflicts may happen, use try_borrow/try_borrow_mut to handle failures or redesign to use Mutex/RwLock for explicit synchronization.