GB-Power-Market-JJ rust-code-review
Reviews Rust code for ownership, borrowing, lifetime, error handling, trait design, unsafe usage, and common mistakes. Use when reviewing .rs files, checking borrow checker issues, error handling patterns, or trait implementations. Covers Rust 2021 edition patterns and modern idioms.
install
source · Clone the upstream repo
git clone https://github.com/GeorgeDoors888/GB-Power-Market-JJ
Claude Code · Install into ~/.claude/skills/
T=$(mktemp -d) && git clone --depth=1 https://github.com/GeorgeDoors888/GB-Power-Market-JJ "$T" && mkdir -p ~/.claude/skills && cp -r "$T/openclaw-skills/skills/anderskev/rust-code-review" ~/.claude/skills/georgedoors888-gb-power-market-jj-rust-code-review && rm -rf "$T"
OpenClaw · Install into ~/.openclaw/skills/
T=$(mktemp -d) && git clone --depth=1 https://github.com/GeorgeDoors888/GB-Power-Market-JJ "$T" && mkdir -p ~/.openclaw/skills && cp -r "$T/openclaw-skills/skills/anderskev/rust-code-review" ~/.openclaw/skills/georgedoors888-gb-power-market-jj-rust-code-review && rm -rf "$T"
manifest:
openclaw-skills/skills/anderskev/rust-code-review/SKILL.mdsource content
Rust Code Review
Review Workflow
Follow this sequence to avoid false positives and catch edition-specific issues:
- Check
— Note the Rust edition (2018, 2021, 2024) and MSRV if set. This determines which patterns apply. Check workspace structure if present.Cargo.toml - Check dependencies — Note key crates (thiserror vs anyhow, tokio features, serde features). These inform which patterns are expected.
- Scan changed files — Read full functions, not just diffs. Many Rust bugs hide in ownership flow across a function.
- Check each category — Work through the checklist below, loading references as needed.
- Verify before reporting — Load beagle-rust:review-verification-protocol before submitting findings.
Output Format
Report findings as:
[FILE:LINE] ISSUE_TITLE Severity: Critical | Major | Minor | Informational Description of the issue and why it matters.
Quick Reference
| Issue Type | Reference |
|---|---|
| Ownership transfers, borrowing conflicts, lifetime issues | references/ownership-borrowing.md |
| Result/Option handling, thiserror, anyhow, error context | references/error-handling.md |
| Async pitfalls, Send/Sync bounds, runtime blocking | references/async-concurrency.md |
| Unsafe usage, clippy patterns, API design, performance | references/common-mistakes.md |
Review Checklist
Ownership and Borrowing
- No unnecessary
to silence the borrow checker (hiding design issues).clone() - References have appropriate lifetimes (not overly broad
when shorter lifetime works)'static -
preferred over&str
in function parameters when ownership isn't neededString -
orimpl AsRef<T>
used for flexible API parametersInto<T> - No dangling references or use-after-move
- Interior mutability (
,Cell
,RefCell
) used only when shared mutation is genuinely neededMutex - Small types (≤24 bytes) derive
and are passed by valueCopy -
used when ownership is ambiguousCow<'_, T>
Error Handling
-
used for recoverable errors, notResult<T, E>
/panic!
/unwrapexpect - Error types provide context (thiserror with
or manual#[error("...")]
)Display -
operator used with proper?
implementations orFrom.map_err() -
/unwrap()
only in tests, examples, or provably-safe contextsexpect() - Error variants are specific enough to be actionable by callers
-
used in applications,anyhow
in libraries (or clear rationale for alternatives)thiserror -
variants used when fallbacks involve allocation (_or_else
,ok_or_else
)unwrap_or_else -
used for early returns on failure (let-else
)let Ok(x) = expr else { return ... } -
used for error logging,inspect_err
for error transformationmap_err
Traits and Types
- Traits are minimal and cohesive (single responsibility)
-
macros appropriate for the type (derive
,Clone
,Debug
used correctly)PartialEq - Newtypes used to prevent primitive obsession (e.g.,
not barestruct UserId(Uuid)
)Uuid -
/From
implementations are lossless and infallible;Into
for fallible conversionsTryFrom - Sealed traits used when external implementations shouldn't be allowed
- Default implementations provided where they make sense
-
bounds verified for types shared across threadsSend + Sync
Unsafe Code
-
blocks have safety comments explaining invariantsunsafe -
is minimal — only the truly unsafe operation is inside the blockunsafe - Safety invariants are documented and upheld by surrounding safe code
- No undefined behavior (null pointer deref, data races, invalid memory access)
-
trait implementations justify why the contract is upheldunsafe
Naming and Style
- Types are
, functions/methodsPascalCase
, constantssnake_caseSCREAMING_SNAKE_CASE - Modules use
snake_case -
,is_
,has_
prefixes for boolean-returning methodscan_ - Builder pattern methods take and return
(notself
) for chaining&mut self - Public items have doc comments (
)/// -
on functions where ignoring the return value is likely a bug#[must_use] - Imports ordered: std → external crates → workspace → crate/super
-
preferred over#[expect(clippy::...)]
for lint suppression#[allow(...)]
Performance
- No unnecessary allocations in hot paths (prefer
over&str
,String
over&[T]
)Vec<T> -
type is specified or inferablecollect() - Iterators preferred over indexed loops for collection transforms
-
used when size is knownVec::with_capacity() - No redundant
/.to_string()
chains.to_owned() - No intermediate
when passing iterators directly works.collect() -
preferred over.sum()
for summation.fold() - Static dispatch (
) used over dynamic (impl Trait
) unless flexibility requireddyn Trait
Linting
-
passescargo clippy --all-targets --all-features -- -D warnings - Key lints respected:
,redundant_clone
,large_enum_variantneedless_collect - Workspace lint configuration in
for consistent enforcementCargo.toml - Doc lints enabled for library crates (
,missing_docs
)broken_intra_doc_links
Severity Calibration
Critical (Block Merge)
code with unsound invariants or undefined behaviorunsafe- Use-after-free or dangling reference patterns
on user input or external data in production codeunwrap()- Data races (concurrent mutation without synchronization)
- Memory leaks via circular
without weak referencesArc<Mutex<...>>
Major (Should Fix)
- Errors returned without context (bare
equivalent)return err
masking ownership design issues in hot paths.clone()- Missing
/Send
bounds on types used across threadsSync
for recoverable errors in library codepanic!- Overly broad
lifetimes hiding API design issues'static
Minor (Consider Fixing)
- Missing doc comments on public items
parameter whereString
or&str
would workimpl AsRef<str>- Derive macros missing for types that should have them
- Unused feature flags in
Cargo.toml - Suboptimal iterator chains (multiple allocations where one suffices)
Informational (Note Only)
- Suggestions to introduce newtypes for domain modeling
- Refactoring ideas for trait design
- Performance optimizations without measured impact
- Suggestions to add
or#[must_use]#[non_exhaustive]
When to Load References
- Reviewing ownership transfers, borrows, or lifetimes → ownership-borrowing.md
- Reviewing Result/Option handling or error types → error-handling.md
- Reviewing async code, tokio usage, or Send/Sync bounds → async-concurrency.md
- General review (unsafe, performance, API design, clippy) → common-mistakes.md
Valid Patterns (Do NOT Flag)
These are acceptable Rust patterns — reporting them wastes developer time:
in tests — Clarity over performance in test code.clone()
in tests and examples — Acceptable where panicking on failure is intentionalunwrap()
in simple binaries — Not every application needs custom error typesBox<dyn Error>
fields in structs — Owned data in structs is correct;String
fields require lifetime parameters&str
during development — Common during iteration#[allow(dead_code)]
/todo!()
in new code — Valid placeholder during active developmentunimplemented!()
with clear message — Self-documenting and acceptable for invariants.expect("reason")
in test modules — Standard pattern foruse super::*
modules#[cfg(test)]- Type aliases for complex types —
is idiomatictype Result<T> = std::result::Result<T, MyError>
in return position — Zero-cost abstraction, standard patternimpl Trait- Turbofish syntax —
is idiomatic when type inference needs helpcollect::<Vec<_>>()
prefix for intentionally unused variables — Compiler convention_
with justification — Self-cleaning lint suppression#[expect(clippy::...)]
— Explicit Arc cloning is idiomatic and recommendedArc::clone(&arc)
for short critical sections in async — Tokio docs recommend thisstd::sync::Mutex
loops over iterators — When early exit or side effects are neededfor
Context-Sensitive Rules
Only flag these issues when the specific conditions apply:
| Issue | Flag ONLY IF |
|---|---|
| Missing error context | Error crosses module boundary without context |
Unnecessary | In hot path or repeated call, not test/setup code |
| Missing doc comments | Item is and not in a module |
usage | In production code path, not test/example/provably-safe |
Missing | Type is actually shared across thread/task boundaries |
| Overly broad lifetime | A shorter lifetime would work AND the API is public |
Missing | Function returns a value that callers commonly ignore |
Stale suppression | Should be for self-cleaning lint management |
Missing derive | Type is ≤24 bytes with all-Copy fields and used frequently |
Before Submitting Findings
Load and follow
beagle-rust:review-verification-protocol before reporting any issue.