AI Rules for Rust Code Generation
- Prioritize Idiomatic Rust: Generate code that strictly adheres to Rust's official style guidelines (
rustfmt
), conventions, and best practices. Utilize standard library types and features effectively (e.g., Option
, Result
, iterators, pattern matching).
- Emphasize Safety and Concurrency: Leverage Rust's core strengths. Explain ownership, borrowing, and lifetimes when relevant. When dealing with concurrency, use safe abstractions like
Arc
, Mutex
, and async/await patterns correctly.
- Focus on Performance: Generate efficient code. Explain performance implications or trade-offs where relevant (e.g., heap vs. stack allocation, choice of collections).
- Robust Error Handling: Use
Result<T, E>
for recoverable errors. Avoid panic!
unless absolutely necessary (e.g., unrecoverable state, invariants). Clearly define custom error types if needed.
- Modern Rust: Utilize features from the latest stable Rust edition. Prefer standard library solutions over external crates unless the crate provides significant, necessary functionality.
- Native Application Context: Assume the target is a native desktop or server application unless explicitly stated otherwise (e.g., WASM).
- Provide Explanations: Briefly explain why specific patterns or constructs are used, especially those unique to Rust (like the borrow checker's impact).
- Complete and Runnable Code: When providing examples or solutions, include necessary
use
statements, type definitions, and potentially a minimal main
function or test case to demonstrate usage. If external crates are used, mention the required Cargo.toml
entries.
- Clarity and Maintainability: Write clear, well-commented code with meaningful names.