---
name: rust-anti-patterns
description: "Common Rust anti-patterns to avoid, focusing on idiomatic Rust and safety."
language: rust
---

# Rust Anti-patterns

Common pitfalls and anti-patterns to avoid in Rust development, ensuring safety and idiomatic code.

## Guidelines
- **Avoid overusing `unwrap()` and `expect()`**: Prefer proper error handling with `Result` or `Option`. Use them only in tests or when you are certain that a failure is impossible.
- **Don't use `RefCell` when simple ownership or borrowing works**: It introduces runtime overhead and potential panics.
- **Avoid excessive cloning**: Instead of `.clone()`, try to restructure code to use references or pass ownership.
- **Don't use `Box` for everything**: Only use heap allocation when necessary (e.g., large structs, recursive types, trait objects).
- **Avoid `unsafe` unless strictly necessary**: Always document why `unsafe` is used and ensure the safety invariants are upheld.
- **Don't ignore compiler warnings**: Treat warnings as errors, especially those from Clippy.
- **Avoid "stringly-typed" APIs**: Use enums and structs instead of raw strings to represent different states or configurations.
- **Don't use `pub` on everything**: Keep fields and methods private by default to maintain encapsulation.

## Tools & Libraries
- **Clippy**: The standard Rust linter for identifying anti-patterns.
- **Rust-analyzer**: For real-time feedback and refactoring.
- **cargo-audit**: To check for vulnerabilities in dependencies.
- **cargo-deny**: To manage dependencies and licenses.

## Trigger Scenarios
- When reviewing Rust code that uses `unwrap()` frequently.
- When an implementation seems unnecessarily complex or non-idiomatic.
- When `clone()` is used excessively to bypass borrow checker issues.
- When a developer asks how to avoid common Rust pitfalls.

<!-- synapsis-dsai-managed -->
