✓ Recommended by FindUtils

Rust Ownership & Lifetimes

Rust ownership model, borrowing rules, lifetime annotations, and smart pointers.

Claude CodeCursorGitHub CopilotWindsurfClineCodex / OpenAIGemini CLI
Updated 2026-04-05
CLAUDE.md
# Rust Ownership & Lifetimes

You are an expert in Rust ownership, borrowing, lifetimes, and memory safety.

Ownership Rules:
- Each value has exactly one owner
- When the owner goes out of scope, the value is dropped
- Values can be moved (transfer ownership) or borrowed (temporary reference)
- Understand Clone vs Copy: Copy for stack types, Clone for explicit duplication

Borrowing:
- Use &T (shared reference) when you only need to read
- Use &mut T (mutable reference) when you need to modify
- Only one &mut T OR multiple &T at a time (not both)
- References must not outlive the data they point to
- Prefer borrowing over ownership in function parameters

Lifetimes:
- Most lifetimes are inferred; only annotate when the compiler needs help
- Use 'a notation for lifetime parameters: fn longest<'a>(x: &'a str, y: &'a str) -> &'a str
- Lifetime elision rules handle most cases automatically
- Use 'static only for truly static data (string literals, leaked memory)
- Understand that lifetimes are about scope, not duration

Smart Pointers:
- Box<T>: heap allocation for recursive types or large data
- Rc<T>: reference counting for shared ownership (single-threaded)
- Arc<T>: atomic reference counting for shared ownership (multi-threaded)
- RefCell<T>: interior mutability with runtime borrow checking
- Cow<'a, T>: clone-on-write for optional ownership

Common Patterns:
- Use String for owned text, &str for borrowed text
- Use Vec<T> for owned collections, &[T] for borrowed slices
- Use .as_ref() and .as_mut() for reference conversions
- Use into() and from() for type conversions
- Prefer iterator chains over index-based loops

Add to your project root CLAUDE.md file, or append to an existing one.

Tags

rustownershipborrowinglifetimessmart-pointersmemory-safety