Rust Code Review
by @anderskev
Reviews Rust code for ownership, borrowing, lifetime, error handling, trait design, unsafe usage, and common mistakes. Use when reviewing .rs files, checking...
clawhub install rust-code-reviewπ About This Skill
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:
1. 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.
2. Check dependencies β Note key crates (thiserror vs anyhow, tokio features, serde features). These inform which patterns are expected.
3. Scan changed files β Read full functions, not just diffs. Many Rust bugs hide in ownership flow across a function.
4. Check each category β Work through the checklist below, loading references as needed.
5. 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.
1. 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.
2. 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).
3. 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.
4. 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
.clone() to silence the borrow checker (hiding design issues).clone() inside loops β prefer .cloned() or .copied() on iterators'static when shorter lifetime works)-> impl Trait) captures all in-scope lifetimes by default; use + use<'a> for precise capture control&str preferred over String, &[T] over Vec in function parametersimpl AsRef or Into used for flexible API parametersCell, RefCell, Mutex) used only when shared mutation is genuinely neededCopy and are passed by valueCow<'_, T> used when ownership is ambiguous.collect() β pass iterators directly when the consumer accepts them.sum() preferred over .fold() for summation (compiler optimizes better)_or_else variants used when fallbacks involve allocationif let temporaries drop at end of the if let β code relying on temporaries living through the else branch needs restructuringBox<[T]> implements IntoIterator β prefer direct iteration over into_vec() firstError Handling
Result used for recoverable errors, not panic!/unwrap/expect#[error("...")] or manual Display)? operator used with proper From implementations or .map_err()unwrap() / expect() only in tests, examples, or provably-safe contextsanyhow used in applications, thiserror in libraries (or clear rationale for alternatives)_or_else variants used when fallbacks involve allocation (ok_or_else, unwrap_or_else)let-else used for early returns on failure (let Ok(x) = expr else { return ... })inspect_err used for error logging, map_err for error transformationTraits and Types
derive macros appropriate for the type (Clone, Debug, PartialEq used correctly)struct UserId(Uuid) not bare Uuid)From/Into implementations are lossless and infallible; TryFrom for fallible conversionsSend + Sync bounds verified for types shared across threads#[diagnostic::on_unimplemented] used on public traits to provide clear error messages when users forget to implement themUnsafe Code
unsafe blocks have safety comments explaining invariantsunsafe is minimal β only the truly unsafe operation is inside the blockunsafe trait implementations justify why the contract is upheldunsafe fn bodies use explicit unsafe {} blocks around unsafe ops (unsafe_op_in_unsafe_fn is deny)extern "C" {} blocks written as unsafe extern "C" {}#[no_mangle] and #[export_name] written as #[unsafe(no_mangle)] and #[unsafe(export_name)]Naming and Style
PascalCase, functions/methods snake_case, constants SCREAMING_SNAKE_CASEsnake_caseis_, has_, can_ prefixes for boolean-returning methodsself (not &mut self) for chaining///)#[must_use] on functions where ignoring the return value is likely a bug#[expect(clippy::...)] preferred over #[allow(...)] for lint suppressionPerformance
> Detailed guidance:beagle-rust:rust-best-practices skill (references/performance.md)
&str over String, &[T] over Vec)collect() type is specified or inferableVec::with_capacity() used when size is known.to_string() / .to_owned() chains.collect() when passing iterators directly works.sum() preferred over .fold() for summationimpl Trait) used over dynamic (dyn Trait) unless flexibility requiredClippy Configuration
> Detailed guidance:beagle-rust:rust-best-practices skill (references/clippy-config.md)
Cargo.toml ([workspace.lints.clippy] or [lints.clippy])#[expect(clippy::lint)] used over #[allow(...)] β warns when suppression becomes staleredundant_clone, large_enum_variant, needless_collect, perf groupcargo clippy --all-targets --all-features -- -D warnings passesmissing_docs, broken_intra_doc_links)Type State Pattern
> Detailed guidance:beagle-rust:rust-best-practices skill (references/type-state-pattern.md)
PhantomData used for zero-cost compile-time state machines (not runtime enums/booleans)self and return new state type (prevents reuse of old state)Severity Calibration
Critical (Block Merge)
unsafe code with unsound invariants or undefined behaviorunwrap() on user input or external data in production codeArc> without weak referencesMajor (Should Fix)
return err equivalent).clone() masking ownership design issues in hot pathsSend/Sync bounds on types used across threadspanic! for recoverable errors in library code'static lifetimes hiding API design issuesMinor (Consider Fixing)
String parameter where &str or impl AsRef would workCargo.tomlInformational (Note Only)
#[must_use] or #[non_exhaustive]When to Load References
beagle-rust:rust-best-practices skillValid Patterns (Do NOT Flag)
These are acceptable Rust patterns β reporting them wastes developer time:
.clone() in tests β Clarity over performance in test codeunwrap() in tests and examples β Acceptable where panicking on failure is intentionalBox in simple binaries β Not every application needs custom error typesString fields in structs β Owned data in structs is correct; &str fields require lifetime parameters#[allow(dead_code)] during development β Common during iterationtodo!() / unimplemented!() in new code β Valid placeholder during active development.expect("reason") with clear message β Self-documenting and acceptable for invariantsuse super::* in test modules β Standard pattern for #[cfg(test)] modulestype Result = std::result::Result is idiomaticimpl Trait in return position β Zero-cost abstraction, standard patterncollect::>() is idiomatic when type inference needs help_ prefix for intentionally unused variables β Compiler convention#[expect(clippy::...)] with justification β Self-cleaning lint suppressionArc::clone(&arc) β Explicit Arc cloning is idiomatic and recommendedstd::sync::Mutex for short critical sections in async β Tokio docs recommend thisfor loops over iterators β When early exit or side effects are neededasync fn in trait definitions β Stable since 1.75; async-trait crate only needed for dyn Trait or pre-1.75 MSRVLazyCell / LazyLock from std β Stable since 1.80; replaces once_cell and lazy_static for new code+ use<'a, T> precise capture syntax β Edition 2024 syntax for controlling RPIT lifetime captureContext-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 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.