.mdc Rust Backend

Rust イディオマティック・ベストプラクティス

包括的なRustコーディング標準。型安全、エラーハンドリング、テストパターン、パフォーマンス重視の開発。

.mdc · 44 lines
# Rust Best Practices

## Code Organization
- Organize modules by feature or functionality, not by separating types from implementations.
- Keep structs and their `impl` blocks together in the same module.
- Design small, focused structs rather than monolithic types.
- Decompose complex data into composable pieces to improve borrow-checker ergonomics.

## Type Safety
- Wrap primitive types in newtype structs to enforce strong typing and prevent logical errors from mixing incompatible IDs.
- Use the Builder pattern for structs with many optional fields, but don't overuse it for simple types.
- Apply generic bounds minimally on type definitions; reserve stricter bounds for `impl` blocks where they're actually needed.

## Error Handling
- Always use `Result<T, E>` for errors that can be handled or propagated.
- Create domain-specific error enums with `thiserror`.
- Reserve panics for unrecoverable bugs only.
- Every `unsafe` block requires a `// SAFETY:` comment documenting why the code upholds Rust's invariants.
- Use `.expect("reason")` instead of `.unwrap()` in non-test code.

## Performance
- Start with `Vec` and `HashMap` as defaults; only switch to alternatives when profiling reveals bottlenecks.
- Pre-allocate collection capacity when sizes are known to minimize reallocations.
- Use `Cow<'_, str>` to avoid unnecessary cloning of strings.
- Prefer `&str` over `String` in function parameters when ownership isn't needed.
- Use `#[inline]` judiciously — only on small, hot-path functions.

## Testing
- Use `#[test]` for unit tests co-located with source code.
- Leverage `rustdoc` examples to keep documentation executable and accurate.
- Use table-driven tests with arrays of (input, expected) tuples.
- Test both success and error paths.
- Use `proptest` or `quickcheck` for property-based testing.

## Dependencies
- Keep `Cargo.toml` dependencies minimal.
- Use `cargo audit` regularly to check for security vulnerabilities.
- Pin exact versions in applications; use semver ranges in libraries.
- Prefer well-maintained crates with active communities.

## Formatting and Linting
- Run `cargo fmt` before every commit.
- Enable `cargo clippy` with `-D warnings` in CI.
- Use `#[allow(clippy::...)]` sparingly with a comment explaining why.
Share on X

こちらもおすすめ

Backend カテゴリの他のルール

もっとルールを探す

CLAUDE.md、.cursorrules、AGENTS.md、Image Prompts の全 157 ルールをチェック。