| name | rust-code-review |
| description | 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 2024 edition patterns and modern idioms. |
Rust Code Review
Review Workflow
Follow this sequence to avoid false positives and catch edition-specific issues:
- Check
Cargo.toml — Note the Rust edition (2018, 2021, 2024) and MSRV if set. Edition 2024 introduces breaking changes to unsafe semantics, RPIT lifetime capture, temporary scoping, and ! type fallback. This determines which patterns apply. Check workspace structure if present.
- 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 — Complete Gates (below), including the verification-protocol gate, before submitting findings.
Gates
These steps are sequenced: do not skip ahead with “mental verification.” Each step has an objective Pass you can satisfy from files on disk and your own read path.
- Crate context — Before relying on edition-specific checklist rows (Edition 2024, MSRV-sensitive APIs) or dependency assumptions. Pass: You opened the relevant
Cargo.toml (package or workspace manifest) and can state edition and rust-version (if set) in one line.
- Expanded read — Before reporting a Major or Critical finding. Pass: You read the full function,
unsafe block, or impl / trait item that contains the cited line (not only a diff hunk).
- Severity match — Before each finding line in the report. Pass: The Severity label matches Severity Calibration for that issue class, or you use Informational and give a one-line rationale.
- Verification protocol — Before finalizing the report. Pass:
beagle-rust:review-verification-protocol is loaded and every step in it that applies to this review is completed (do not substitute a vague “I checked”).
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, lifetimes, clone traps, iterators | references/ownership-borrowing.md |
| Lifetime variance, covariance/invariance, memory regions | references/lifetime-variance.md |
| Result/Option handling, thiserror, anyhow, error context, Error trait | references/error-handling.md |
| Async pitfalls, Send/Sync bounds, runtime blocking | references/async-concurrency.md |
| Send/Sync semantics, atomics, memory ordering, lock patterns | references/concurrency-primitives.md |
| Type layout, alignment, repr, PhantomData, generics vs dyn Trait | references/types-layout.md |
| Unsafe code, API design, derive patterns, clippy patterns | references/common-mistakes.md |
| Safety contracts, raw pointers, MaybeUninit, soundness, Miri | references/unsafe-deep.md |
For development guidance on performance, pointer types, type state, clippy config, iterators, generics, and documentation, use the beagle-rust:rust-best-practices skill.
Review Checklist
Ownership and Borrowing
Error Handling
Traits and Types
Unsafe Code
Naming and Style
Performance
Detailed guidance: beagle-rust:rust-best-practices skill (references/performance.md)
Clippy Configuration
Detailed guidance: beagle-rust:rust-best-practices skill (references/clippy-config.md)
Type State Pattern
Detailed guidance: beagle-rust:rust-best-practices skill (references/type-state-pattern.md)
Severity Calibration
Critical (Block Merge)
unsafe code with unsound invariants or undefined behavior
- Use-after-free or dangling reference patterns
unwrap() on user input or external data in production code
- Data races (concurrent mutation without synchronization)
- Memory leaks via circular
Arc<Mutex<...>> without weak references
Major (Should Fix)
- Errors returned without context (bare
return err equivalent)
.clone() masking ownership design issues in hot paths
- Missing
Send/Sync bounds on types used across threads
panic! for recoverable errors in library code
- Overly broad
'static lifetimes hiding API design issues
Minor (Consider Fixing)
- Missing doc comments on public items
String parameter where &str or impl AsRef<str> would work
- 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
#[must_use] or #[non_exhaustive]
When to Load References
- Reviewing ownership, borrows, lifetimes, clone traps → ownership-borrowing.md
- Reviewing lifetime variance, covariance/invariance, multiple lifetime params → lifetime-variance.md
- Reviewing Result/Option handling, error types, Error trait impls → error-handling.md
- Reviewing async code, tokio usage, task management → async-concurrency.md
- Reviewing Send/Sync, atomics, memory ordering, mutexes, lock patterns → concurrency-primitives.md
- Reviewing type layout, alignment, repr, PhantomData, generics vs dyn → types-layout.md
- Reviewing unsafe code, API design, derive macros, clippy patterns → common-mistakes.md
- Reviewing safety contracts, raw pointers, MaybeUninit, soundness → unsafe-deep.md
- Reviewing performance, pointer types, type state, generics, iterators, documentation →
beagle-rust:rust-best-practices skill
Valid Patterns (Do NOT Flag)
These are acceptable Rust patterns — reporting them wastes developer time:
.clone() in tests — Clarity over performance in test code
unwrap() in tests and examples — Acceptable where panicking on failure is intentional
Box<dyn Error> in simple binaries — Not every application needs custom error types
String fields in structs — Owned data in structs is correct; &str fields require lifetime parameters
#[allow(dead_code)] during development — Common during iteration
todo!() / unimplemented!() in new code — Valid placeholder during active development
.expect("reason") with clear message — Self-documenting and acceptable for invariants
use super::* in test modules — Standard pattern for #[cfg(test)] modules
- Type aliases for complex types —
type Result<T> = std::result::Result<T, MyError> is idiomatic
impl Trait in return position — Zero-cost abstraction, standard pattern
- Turbofish syntax —
collect::<Vec<_>>() is idiomatic when type inference needs help
_ prefix for intentionally unused variables — Compiler convention
#[expect(clippy::...)] with justification — Self-cleaning lint suppression
Arc::clone(&arc) — Explicit Arc cloning is idiomatic and recommended
std::sync::Mutex for short critical sections in async — Tokio docs recommend this
for loops over iterators — When early exit or side effects are needed
async fn in trait definitions — Stable since 1.75; async-trait crate only needed for dyn Trait or pre-1.75 MSRV
LazyCell / LazyLock from std — Stable since 1.80; replaces once_cell and lazy_static for new code
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 .clone() | In hot path or repeated call, not test/setup code |
| Missing doc comments | Item is pub and not in a #[cfg(test)] module |
unwrap() usage | In production code path, not test/example/provably-safe |
Missing Send + Sync | Type is actually shared across thread/task boundaries |
| Overly broad lifetime | A shorter lifetime would work AND the API is public |
Missing #[must_use] | Function returns a value that callers commonly ignore |
Stale #[allow] suppression | Should be #[expect] for self-cleaning lint management |
Missing Copy derive | Type is ≤24 bytes with all-Copy fields and used frequently |
Edition 2024: ! type fallback | Match on Result<T, !> or diverging expressions where () fallback was assumed — ! now falls back to ! not () |
Edition 2024: r#gen identifier | Code uses gen as an identifier — must be r#gen in edition 2024 (reserved keyword) |
Before Submitting Findings
Satisfy Gates § verification protocol (step 4). Load and follow beagle-rust:review-verification-protocol before reporting any issue.