---
name: rust-resource-management
description: "Resource management in Rust using ownership, borrowing, and RAII patterns."
language: rust
---

# Rust Resource Management

Mastering memory and resource safety in Rust through its unique ownership system.

## Guidelines
- **Understand Ownership**: Follow the rules of one owner, many immutable borrows, or one mutable borrow.
- **Use RAII (Resource Acquisition Is Initialization)**: Ensure resources (files, sockets, memory) are automatically released when their owner goes out of scope.
- **Smart Pointers**:
  - `Box<T>` for heap allocation.
  - `Rc<T>` / `Arc<T>` for shared ownership.
  - `RefCell<T>` / `Mutex<T>` for interior mutability.
- **Avoid Memory Leaks**: Be careful with circular references when using `Rc` or `Arc`; use `Weak` to break cycles.
- **Lifetime Management**: Use explicit lifetimes only when the compiler cannot infer them, and keep them as simple as possible.
- **Efficient Buffer Management**: Use `Vec::with_capacity` to prevent multiple reallocations.

## Tools & Libraries
- **Miri**: To check for undefined behavior and memory leaks in unsafe code.
- **Valgrind**: For identifying memory issues in complex scenarios.
- **clippy**: To catch common resource management mistakes.

## Trigger Scenarios
- When dealing with complex lifetimes or borrow checker errors.
- When managing system resources like file handles or network sockets.
- When designing data structures with shared state.
- When a developer asks about memory safety in Rust.

<!-- synapsis-dsai-managed -->
