rust-ownership-optimizer
Guides AI coding agents on Rust ownership, borrowing, lifetimes, and memory optimization; reduces unnecessary clones and allocations by leveraging compile-time ownership analysis. Use when writing, reviewing, or refactoring Rust code, when fixing borrow checker errors (E0382, E0499, E0502, E0505, E0506, E0507, E0515, E0597, E0716, E0106), or when code contains `.clone()`, `Box`, `Rc`, `RefCell`, `Arc`, `Mutex`, `to_string()`, or `to_owned()`.
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Badge for your README
Markdown
[](/listings/ichbinrather--rust-ownership-optimizer)HTML
<a href="/listings/ichbinrather--rust-ownership-optimizer"><img src="/api/listings/ichbinrather--rust-ownership-optimizer/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
Windows
git clone https://github.com/ichbinrather/rust-ownership-optimizer.git cd rust-ownership-optimizer powershell -ExecutionPolicy Bypass -File .\install.ps1
macOS / Linux
git clone https://github.com/ichbinrather/rust-ownership-optimizer.git cd rust-ownership-optimizer ./install.sh
The script looks for the config folders of the supported agents (`.claude`, `.codex`, `.cursor`, ...) in your home directory and copies the skill into each one it finds. Restart the agent afterwards.
Options:
- `-Link` / `--link`: link to the clone instead of copying it, so `git pull` updates the skill. On Windows this creates a directory junction, which does not need admin rights. - `-All` / `--all`: also install for agents whose folder does not exist yet. - `-Force` / `--force`: overwrite an existing install.
If you have Node.js, `npx skills add ichbinrather/rust-ownership-optimizer` works too.
Installing by hand
Copy the repository into the agent's skills folder under the name `rust-ownership-optimizer`, so that `SKILL.md` ends up directly inside it.
| Agent | Skills folder | |-------|---------------| | Claude Code | `~/.claude/skills` | | Codex CLI | `~/.codex/skills` or `~/.agents/skills` | | OpenCode | `~/.config/opencode/skills` | | Cursor | `~/.cursor/skills` | | Gemini CLI | `~/.gemini/skills` | | GitHub Copilot | `~/.copilot/skills` |
On Windows, `~` is `%USERPROFILE%`. These paths have moved between agent versions before, so check your agent's docs if the skill does not show up.
To use it in a single project, put it in `.claude/skills/` inside the repository and copy `AGENTS.md` to the project root. Agents without skill support can use the rules in `AGENTS.md` directly: paste them into `.github/copilot-instructions.md`, `.cursor/rules/`, `GEMINI.md`, `.windsurf/rules/`, or `.clinerules/`.
Checking that it loaded
Restart the agent and ask which skills it has, or call it by name (`/rust-ownership-optimizer` in Claude Code, `$rust-ownership-optimizer` in Codex). On a Rust project, ask it to review a file for unnecessary clones. Findings come back like this:
[clone] src/report.rs:42: report cloned for a read-only call -> take &Report [box] src/shapes.rs:10: Box<dyn Shape> parameter only borrowed -> &dyn Shape
Updating and removing
With a linked install, `git pull` is enough. With a copied install, pull and run the installer again with `-Force` / `--force`.
To remove it, delete `rust-ownership-optimizer` from the agent's skills folder. If you installed with `-Link` on Windows, remove the junction with `cmd /c rmdir <path>`. In Windows PowerShell 5.1, `Remove-Item -Recurse` on a junction can delete the files in your clone as well.
If PowerShell says that running scripts is disabled, use the `-ExecutionPolicy Bypass` form shown above. It applies to that single run only.
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
SKILL.md · Manifest · 236 lines
- ---
- name: rust-ownership-optimizer
- description: Guides AI coding agents on Rust ownership, borrowing, lifetimes, and memory optimization; reduces unnecessary clones and allocations by leveraging compile-time ownership analysis. Use when writing, reviewing, or refactoring Rust code, when fixing borrow checker errors (E0382, E0499, E0502, E0505, E0506, E0507, E0515, E0597, E0716, E0106), or when code contains `.clone()`, `Box`, `Rc`, `RefCell`, `Arc`, `Mutex`, `to_string()`, or `to_owned()`.
- license: MIT
- metadata:
- version: "0.4.0"
- ---
- # Rust Ownership Optimizer
- ## Core Principle
- Rust has **no garbage collector and no runtime memory manager**. Memory is managed by
- **compile-time ownership analysis**: the compiler (borrow checker) proves at compile time
- who owns each value, how long each reference lives, and exactly where each value is
- dropped. Deallocation is deterministic and inserted by the compiler at scope end (RAII).
- Never describe Rust memory management with terms borrowed from runtime-managed
- languages. Never write "the value is collected", "the collector frees it", or similar.
- Say "the value is dropped at the end of its owner's scope".
- Your goal: produce code that satisfies the borrow checker **by design**, not by
- copying data until the errors disappear.
- ## The Ownership Rules (always apply)
- 1. Each value has exactly one owner.
- 2. When the owner goes out of scope, the value is dropped.
- 3. At any time, a value has **either** any number of shared references (`&T`) **or**
- exactly one mutable reference (`&mut T`), never both.
- 4. A reference must never outlive the value it points to.
- ## Workflow
- Follow these steps for every Rust task in scope.
- 1. **Ask the ownership question first.** Before touching code, answer:
- *Who should own this data, and for how long?* Classify the value:
- - **Unique entity** (has identity, one place of truth): one owner, others borrow.
- - **Value object** (small, interchangeable): `Copy` or a cheap `clone()` is fine.
- - **Shared immutable data** (config, audit records, lookup tables): `Arc<T>` / `Rc<T>`
- or plain `&T` with a lifetime, never deep copies.
- - **Temporary** (intermediate result): restructure so it is never stored.
- 2. **Map the compiler error to a design question**, not to a quick fix.
- See `references/error-codes.md`.
- 3. **Apply the review checklist** below.
- 4. **Verify** with `cargo check` and Clippy (see Verification).
- 5. **Check your own diff** with the ownership guard before you finish (see Diff Guard).
- This matters most when the borrow error was a side issue in a larger task.
- 6. **Escalate after three failed attempts.** If the same borrow error survives three
- local fixes, stop patching. Re-examine the data model: ownership roles, struct
- boundaries, or whether the data should be split, indexed, or shared.
- ## Decision Order for Parameters and Fields
- Pick the **first** option that compiles and expresses the intent:
- | Need | Use | Runtime cost |
- |------|-----|--------------|
- | Read only | `&T`, `&str`, `&[T]`, `&Path` | none |
- | Modify in place | `&mut T` | none |
- | Store or consume the value | `T` (caller moves in) | none (move) |
- | Usually borrowed, sometimes modified | `Cow<'_, T>` | allocation only on write |
- | Accept many input types | `impl AsRef<T>` / `impl Into<T>` | none / conversion |
- | Shared ownership, single thread | `Rc<T>` | non-atomic count |
- | Shared ownership, multi thread | `Arc<T>` | atomic count |
- | Mutation behind shared ownership | `Cell` / `RefCell` / `Mutex` / `RwLock` | runtime check (last resort) |
- Prefer borrowed slice types in signatures: `&str` over `&String`, `&[T]` over `&Vec<T>`,
- `&Path` over `&PathBuf`.
- ## Review Checklist
- ### 1. Unnecessary `clone()`
- Flag a `.clone()` (or `.to_string()`, `.to_owned()`, `.to_vec()`) when:
- - The clone is passed to a function that only reads it. Fix: change the parameter to `&T`.
- - The original is never used after the clone. Fix: move the original instead.
- - The clone exists only to silence E0382 (use after move). Fix: reorder code, borrow, or
- restructure so the last use moves.
- - The clone is inside a loop over a collection that could be iterated by reference
- (`for x in &items`) or consumed (`for x in items`).
- - A `String` is cloned only to be compared or hashed. Fix: compare `&str`.
- - An `Option<T>` / `Result<T, E>` is cloned to inspect it. Fix: `.as_ref()`, `.as_deref()`,
- `if let Some(x) = &opt`.
- - A struct field is cloned out to call a method while `self` is borrowed. Fix: borrow
- disjoint fields separately, or use `std::mem::take` / `std::mem::replace`.
- A clone is **justified** when: the value is a cheap value object, two owners genuinely
- need independent copies, the data crosses a thread boundary without `Arc`, or the clone
- is of an `Rc`/`Arc` (a reference-count increment, not a deep copy). Write `Rc::clone(&x)`
- to make that explicit.
- ### 2. Unnecessary `Box`
- Flag `Box<T>` when:
- - `T` is a sized value used only locally (`let x = Box::new(5);`). Use the value directly.
- - `Box<Vec<T>>`, `Box<String>`, `Box<HashMap<..>>`: these already own heap storage.
- - A parameter is `Box<dyn Trait>` but the function only uses the value during the call.
- Take a reference instead: `&dyn Trait` or `&impl Trait`. Both avoid the allocation.
- - A function returns `Box<dyn Iterator>` where `impl Iterator` works.
- `&dyn Trait` and generics are both fine; the problem is the `Box`, not the `dyn`. Do not
- rewrite working `&dyn` code into generics just for static dispatch. Prefer generics only
- when the call is in a measured hot path, and keep `&dyn` when it avoids duplicated code
- from monomorphization or keeps compile times and binary size down.
- `Box` is **justified** for: recursive types (`enum List { Cons(i32, Box<List>), Nil }`),
- heterogeneous collections of trait objects, very large values moved often, and
- `Box<dyn Error>` at application boundaries.
- ### 3. Borrow Conflicts
- Fix these patterns without cloning:
- - **Shared + mutable overlap (E0502, E0499):** finish the read, keep the small value you
- need (an index, a `Copy` value, `len()`), then mutate. A borrow ends at its last use
- (non-lexical lifetimes), so shorten the borrow instead of copying the data.
- - **Mutating a collection while iterating it:** use `retain`, `retain_mut`, `drain(..)`,
- `iter_mut()`, `split_at_mut`, or collect indices first and apply after.
- - **Two fields of `self`:** access fields directly (`&mut self.a`, `&self.b`) instead of
- through getters that borrow all of `self`.
- - **Map lookup then insert:** use the `entry()` API.
- - **Moving out of a reference (E0507):** use `std::mem::take`, `mem::replace`,
- `Option::take`, or borrow the inner value.
- - **Value does not live long enough (E0597, E0716, E0515):** bind temporaries to a name,
- move the owner to a wider scope, or return owned data.
- ### 4. Allocations
- Measure before micro-optimizing: algorithm and data structure choices outweigh
- allocation tweaks. Then:
- - Pre-size: `Vec::with_capacity(n)`, `String::with_capacity(n)`.
- - Avoid `collect::<Vec<_>>()` when the result is iterated once: chain iterators.
- - Build strings with `push_str` / `write!` in loops, not repeated `format!` or `+`.
- - Return `&str` / `&[T]` views into existing data instead of new `String` / `Vec`.
- - Use `Cow<'_, str>` when a function usually returns its input unchanged.
- - Benchmark only in `--release`.
- ### 5. Lifetimes
- - Rely on lifetime elision first. Add explicit lifetimes only when the compiler needs them.
- - Never use `'static` to silence an error unless the data truly lives for the whole program.
- - A struct holding references (`struct Parser<'a> { input: &'a str }`) avoids copying.
- Use it for short-lived views.
- - If annotations grow complex, reconsider ownership: the struct may need to own its data.
- ### 6. Smart Pointers and Interior Mutability
- - `Rc<RefCell<T>>` everywhere signals an ownership design problem. Try a single owner
- with borrowed access, an arena with indices, or message passing first.
- - `RefCell` moves borrow checks to runtime and can panic. State why compile-time checks
- are not possible before using it. Prefer `Cell<T>` for `Copy` values.
- - Read-heavy `Arc<Mutex<T>>`: consider `RwLock`, or share an immutable `Arc<T>`.
- - Break reference cycles with `Weak<T>`, or the values are never dropped.
- ## Output Format
- When reviewing code, report each finding as:
- ```
- [category] location: problem -> fix (why it is cheaper or safer)
- ```
- Categories: `clone`, `box`, `borrow`, `alloc`, `lifetime`, `smart-ptr`.
- Then show the optimized code. Keep behavior identical. If a change alters the public
- API (for example a `String` parameter becomes `&str`), say so.
- ## Verification
- Run when a Cargo project is available. The commands work the same in PowerShell, cmd,
- and POSIX shells:
- ```
- cargo check
- cargo clippy --all-targets -- -W clippy::redundant_clone -W clippy::implicit_clone -W clippy::unnecessary_to_owned -W clippy::needless_pass_by_value -W clippy::box_collection -W clippy::boxed_local
- cargo test
- ```
- For the full ownership lint set, run the bundled script from the project root:
- `scripts/audit.ps1` on Windows, `scripts/audit.sh` on macOS and Linux.
- `clippy::redundant_clone` and `clippy::needless_collect` are in Clippy's nursery group
- and can report false positives. Confirm each finding against the rules above before
- changing code.
- Do not claim an optimization compiles until `cargo check` passes. If no toolchain is
- available, say that the code was not compiled.
- ## Diff Guard
- Shortcuts rarely happen when the task is "fix this borrow error". They happen when a
- borrow error interrupts other work and the quickest way back is a `.clone()`. The guard
- lists only the workarounds **you added** in the current change, so it stays quiet on
- existing code.
- Run it from inside the git repository before reporting the task as done:
- ```
- python <skill folder>/scripts/ownership_guard.py
- ```
- Use `python3` where `python` is not available. It flags new `.clone()`, `.to_owned()`,
- `.to_vec()`, `Rc<RefCell<_>>`, `Arc<Mutex<_>>`, `'static`, `Box::leak`, `unsafe`, and
- boxed collections. `Rc::clone(&x)` and `Arc::clone(&x)` are not flagged.
- For every finding, do one of two things:
- - Fix it using the checklist above.
- - Keep it and add a specific justification on the same line or the line above:
- `// ownership: worker thread needs its own copy`. The reason must say why a borrow
- or a move does not work here. Never add a vague comment just to silence the guard.
- If a hook already ran the guard after your edit, treat its output the same way.
- ## Anti-Patterns to Refuse
- - Adding `.clone()` at every error site until the code compiles.
- - Wrapping values in `Rc<RefCell<_>>` to escape the borrow checker.
- - Using `unsafe` to bypass borrow rules.
- - Changing a lifetime to `'static` or leaking memory (`Box::leak`) to fix a lifetime error.
- ## References
- - `references/error-codes.md`: borrow checker error codes, the design question behind
- each, and fixes that avoid copying. Read when a compiler error is present.
- - `references/patterns.md`: closures, threads and async tasks, iterators, conditional
- borrow returns, `Cow`, graphs and arenas. Read when the code uses any of these.
- - `examples/`: compilable before/after programs for clones, `Box`, borrow conflicts,
- and the advanced patterns.
- - `scripts/audit.ps1`, `scripts/audit.sh`: Clippy with the full ownership lint set.
- - `scripts/ownership_guard.py`: lists ownership workarounds added in the current diff.
README.md · README · 252 lines
- # rust-ownership-optimizer
- [](https://github.com/ichbinrather/rust-ownership-optimizer/actions/workflows/ci.yml)
- [](LICENSE)
- A skill for AI coding agents that work on Rust. It stops them from reaching for
- `.clone()`, `Box`, `Rc<RefCell<_>>` or `'static` whenever the borrow checker complains,
- and makes them fix the ownership instead.
- Works with Claude Code, Codex CLI, Cursor, GitHub Copilot, Gemini CLI, OpenCode, and
- anything else that reads `SKILL.md` or `AGENTS.md`.
- <p align="center">
- <img src="assets/demo.svg" alt="An agent fixing E0382: without the skill it clones the value, with the skill it borrows it" width="760">
- </p>
- ## Why
- Ask an agent to fix `error[E0382]: borrow of moved value` and a common answer is:
- ```rust
- print_report(report.clone());
- archive(report);
- ```
- It compiles, and it copies the whole report on every call. `print_report` only reads
- its argument, so the right fix is a borrow:
- ```rust
- fn print_report(report: &Report) { /* ... */ }
- print_report(&report);
- archive(report);
- ```
- The skill gives the agent a short procedure for this kind of decision: work out who
- should own the data, map the compiler error to a design question, go through a
- checklist (clones, boxes, borrow conflicts, allocations, lifetimes, smart pointers),
- and confirm with `cargo check` and Clippy. If the same error survives three attempts,
- it rethinks the data layout instead of adding another workaround.
- ## Install
- ### Windows
- ```powershell
- git clone https://github.com/ichbinrather/rust-ownership-optimizer.git
- cd rust-ownership-optimizer
- powershell -ExecutionPolicy Bypass -File .\install.ps1
- ```
- ### macOS / Linux
- ```bash
- git clone https://github.com/ichbinrather/rust-ownership-optimizer.git
- cd rust-ownership-optimizer
- ./install.sh
- ```
- The script looks for the config folders of the supported agents (`.claude`, `.codex`,
- `.cursor`, ...) in your home directory and copies the skill into each one it finds.
- Restart the agent afterwards.
- Options:
- - `-Link` / `--link`: link to the clone instead of copying it, so `git pull` updates
- the skill. On Windows this creates a directory junction, which does not need admin
- rights.
- - `-All` / `--all`: also install for agents whose folder does not exist yet.
- - `-Force` / `--force`: overwrite an existing install.
- If you have Node.js, `npx skills add ichbinrather/rust-ownership-optimizer` works too.
- ### Installing by hand
- Copy the repository into the agent's skills folder under the name
- `rust-ownership-optimizer`, so that `SKILL.md` ends up directly inside it.
- | Agent | Skills folder |
- |-------|---------------|
- | Claude Code | `~/.claude/skills` |
- | Codex CLI | `~/.codex/skills` or `~/.agents/skills` |
- | OpenCode | `~/.config/opencode/skills` |
- | Cursor | `~/.cursor/skills` |
- | Gemini CLI | `~/.gemini/skills` |
- | GitHub Copilot | `~/.copilot/skills` |
- On Windows, `~` is `%USERPROFILE%`. These paths have moved between agent versions
- before, so check your agent's docs if the skill does not show up.
- To use it in a single project, put it in `.claude/skills/` inside the repository and
- copy `AGENTS.md` to the project root. Agents without skill support can use the rules
- in `AGENTS.md` directly: paste them into `.github/copilot-instructions.md`,
- `.cursor/rules/`, `GEMINI.md`, `.windsurf/rules/`, or `.clinerules/`.
- ### Checking that it loaded
- Restart the agent and ask which skills it has, or call it by name
- (`/rust-ownership-optimizer` in Claude Code, `$rust-ownership-optimizer` in Codex). On a
- Rust project, ask it to review a file for unnecessary clones. Findings come back like
- this:
- ```text
- [clone] src/report.rs:42: report cloned for a read-only call -> take &Report
- [box] src/shapes.rs:10: Box<dyn Shape> parameter only borrowed -> &dyn Shape
- ```
- ### Updating and removing
- With a linked install, `git pull` is enough. With a copied install, pull and run the
- installer again with `-Force` / `--force`.
- To remove it, delete `rust-ownership-optimizer` from the agent's skills folder. If you
- installed with `-Link` on Windows, remove the junction with `cmd /c rmdir <path>`.
- In Windows PowerShell 5.1, `Remove-Item -Recurse` on a junction can delete the files in
- your clone as well.
- If PowerShell says that running scripts is disabled, use the
- `-ExecutionPolicy Bypass` form shown above. It applies to that single run only.
- ## What it covers
- - Clones that only exist to satisfy the compiler: read-only arguments, comparisons,
- loops, inspecting an `Option`.
- - `Box` that adds indirection without a reason: `Box<Vec<T>>`, boxed locals,
- `Box<dyn Trait>` parameters where a reference would do.
- - Borrow checker errors E0382, E0499, E0502, E0505, E0506, E0507, E0515, E0597, E0716,
- E0106 and E0596, with fixes that do not copy data
- ([references/error-codes.md](references/error-codes.md)).
- - Closures, `thread::scope`, `Arc` for spawned tasks, iterator adapters, the "get or
- insert" case the current borrow checker rejects, `Cow`, and index-based graphs
- ([references/patterns.md](references/patterns.md)).
- - Escape hatches it will not use: `'static` to silence a lifetime error, `Box::leak`,
- `unsafe`, and `Rc<RefCell<_>>` everywhere.
- The full instructions are in [SKILL.md](SKILL.md).
- ## Diff guard
- Strong models rarely take the `.clone()` shortcut when the task is "fix this borrow
- error". It happens when a borrow error shows up in the middle of some other task and
- the clone is the fastest way back. `scripts/ownership_guard.py` catches that case: it
- looks only at the lines added in the current change and lists new `.clone()`,
- `.to_owned()`, `.to_vec()`, `Rc<RefCell<_>>`, `Arc<Mutex<_>>`, `'static`, `Box::leak`,
- `unsafe`, and boxed collections. Existing code is ignored.
- ```text
- $ python scripts/ownership_guard.py
- src/game.rs:41: [clone] new .clone(): borrow, move on last use, or share with Arc/Rc instead
- for p in self.players.clone() {
- 1 new ownership workaround(s). For each one, either fix it or add a specific
- justification on the same line or the line above, e.g. `// ownership: snapshot must outlive the lock`.
- ```
- A finding goes away when the line is fixed or carries a reason:
- `// ownership: worker thread needs its own copy`. `Rc::clone(&x)` and `Arc::clone(&x)`
- are never flagged. It needs Python 3.8+ and git, and works on Windows, macOS and Linux.
- The skill tells the agent to run the guard before it finishes. You can also run it
- automatically in three places.
- **After every edit in Claude Code.** Add a hook to `~/.claude/settings.json` (or
- `.claude/settings.json` in a project). The guard's output is sent back to the agent,
- which then fixes or justifies each finding:
- ```json
- {
- "hooks": {
- "PostToolUse": [
- {
- "matcher": "Edit|MultiEdit|Write",
- "hooks": [
- {
- "type": "command",
- "command": "python3 \"$HOME/.claude/skills/rust-ownership-optimizer/scripts/ownership_guard.py\" --hook claude"
- }
- ]
- }
- ]
- }
- }
- ```
- Use `python` instead of `python3` if that is the name on your system, and adjust the
- path if you installed the skill elsewhere.
- **Before every commit.** Save this as `.git/hooks/pre-commit` in your project (on macOS
- and Linux, also run `chmod +x .git/hooks/pre-commit`):
- ```sh
- #!/bin/sh
- python3 path/to/ownership_guard.py --staged
- ```
- **In pull requests.** Copy `ownership_guard.py` into your repository and add a step to
- your GitHub Actions workflow:
- ```yaml
- - uses: actions/checkout@v4
- with:
- fetch-depth: 0
- - run: python3 scripts/ownership_guard.py --base origin/${{ github.base_ref }}
- if: github.event_name == 'pull_request'
- ```
- ## Examples
- Each rule has a before/after program you can run:
- ```text
- cargo run --example unnecessary_clone
- cargo run --example unnecessary_box
- cargo run --example borrow_conflicts
- cargo run --example advanced_patterns
- ```
- To audit your own project with the same Clippy lints the skill uses, run
- `scripts/audit.ps1` (Windows) or `scripts/audit.sh` from the project root.
- ## Evals
- [evals/](evals/) has six small programs with mistakes an agent should catch, together
- with the prompt to give it and what counts as a pass. One of them pushes the agent to
- "just make it compile".
- Results so far, all on Claude Sonnet:
- - When fixing a borrow error **is** the task, Sonnet rarely takes a shortcut with or
- without the skill: 29/30 clean runs without it, 30/30 with it.
- - When the borrow problem shows up **inside a feature task**, it is different. Asked to
- add a game `tick()` that logs and heals players while iterating them, all three runs
- without the skill cloned every player's name on every tick to get past the borrow
- checker. None of the six runs with the skill did.
- That is a small sample and one model. Smaller models are not tested yet. Details, the
- projects, and every patch are in [evals/RESULTS.md](evals/RESULTS.md).
- If you run the evals with another agent or model, please post the results in an issue.
- ## Contributing
- The most useful report is a case where the agent still did the wrong thing with the
- skill installed. There is an issue template for that. For new rules, examples or evals,
- see [CONTRIBUTING.md](CONTRIBUTING.md).
- For broader Rust coverage (error handling, async, domain-specific advice), have a look
- at [actionbook/rust-skills](https://github.com/actionbook/rust-skills).
- ## License
- MIT
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.