Cursor rule
.cursor/rules/rust-patterns.mdcCursor rules
Quality
62/100
Scores the file, not the repository.Length
480 words
9 headings · 7 code blocksRepository
6
— · pushed 80 days agoLast changed
3 days ago
First indexed 3 days ago.12345# Rust Patterns67> This file extends [common/patterns.md](../common/patterns.md) with Rust-specific content.89## Repository Pattern with Traits1011Encapsulate data access behind a trait:1213```rust14pub trait OrderRepository: Send + Sync {15 fn find_by_id(&self, id: u64) -> Result<Option<Order>, StorageError>;16 fn find_all(&self) -> Result<Vec<Order>, StorageError>;17 fn save(&self, order: &Order) -> Result<Order, StorageError>;18 fn delete(&self, id: u64) -> Result<(), StorageError>;19}20```2122Concrete implementations handle storage details (Postgres, SQLite, in-memory for tests).2324## Service Layer2526Business logic in service structs; inject dependencies via constructor:2728```rust29pub struct OrderService {30 repo: Box<dyn OrderRepository>,31 payment: Box<dyn PaymentGateway>,32}3334impl OrderService {35 pub fn new(repo: Box<dyn OrderRepository>, payment: Box<dyn PaymentGateway>) -> Self {36 Self { repo, payment }37 }3839 pub fn place_order(&self, request: CreateOrderRequest) -> anyhow::Result<OrderSummary> {40 let order = Order::from(request);41 self.payment.charge(order.total())?;42 let saved = self.repo.save(&order)?;43 Ok(OrderSummary::from(saved))44 }45}46```4748## Newtype Pattern for Type Safety4950Prevent argument mix-ups with distinct wrapper types:5152```rust53struct UserId(u64);54struct OrderId(u64);5556fn get_order(user: UserId, order: OrderId) -> anyhow::Result<Order> {57 // Can't accidentally swap user and order IDs at call sites58 todo!()59}60```6162## Enum State Machines6364Model states as enums — make illegal states unrepresentable:6566```rust67enum ConnectionState {68 Disconnected,69 Connecting { attempt: u32 },70 Connected { session_id: String },71 Failed { reason: String, retries: u32 },72}7374fn handle(state: &ConnectionState) {75 match state {76 ConnectionState::Disconnected => connect(),77 ConnectionState::Connecting { attempt } if *attempt > 3 => abort(),78 ConnectionState::Connecting { .. } => wait(),79 ConnectionState::Connected { session_id } => use_session(session_id),80 ConnectionState::Failed { retries, .. } if *retries < 5 => retry(),81 ConnectionState::Failed { reason, .. } => log_failure(reason),82 }83}84```8586Always match exhaustively — no wildcard `_` for business-critical enums.8788## Builder Pattern8990Use for structs with many optional parameters:9192```rust93pub struct ServerConfig {94 host: String,95 port: u16,96 max_connections: usize,97}9899impl ServerConfig {100 pub fn builder(host: impl Into<String>, port: u16) -> ServerConfigBuilder {101 ServerConfigBuilder {102 host: host.into(),103 port,104 max_connections: 100,105 }106 }107}108109pub struct ServerConfigBuilder {110 host: String,111 port: u16,112 max_connections: usize,113}114115impl ServerConfigBuilder {116 pub fn max_connections(mut self, n: usize) -> Self {117 self.max_connections = n;118 self119 }120121 pub fn build(self) -> ServerConfig {122 ServerConfig {123 host: self.host,124 port: self.port,125 max_connections: self.max_connections,126 }127 }128}129```130131## Sealed Traits for Extensibility Control132133Use a private module to seal a trait, preventing external implementations:134135```rust136mod private {137 pub trait Sealed {}138}139140pub trait Format: private::Sealed {141 fn encode(&self, data: &[u8]) -> Vec<u8>;142}143144pub struct Json;145impl private::Sealed for Json {}146impl Format for Json {147 fn encode(&self, data: &[u8]) -> Vec<u8> { todo!() }148}149```150151## API Response Envelope152153Consistent API responses using a generic enum:154155```rust156#[derive(Debug, serde::Serialize)]157#[serde(tag = "status")]158pub enum ApiResponse<T: serde::Serialize> {159 #[serde(rename = "ok")]160 Ok { data: T },161 #[serde(rename = "error")]162 Error { message: String },163}164```165166## References167168See skill: `rust-patterns` for comprehensive patterns including ownership, traits, generics, concurrency, and async.169
Also in ThanhTrunggDEV/DontBeLazy
Diff this repo’s formatsOne repository carrying more than one format is the comparison this product exists for: does anyone actually write different content in each file, or is one a copy of the other?
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| ThanhTrunggDEV/DontBeLazy.cursor/rules/zh-agents.mdc · 6 | Cursor rules | no sections | 50/100 | 3 days ago | |
| ThanhTrunggDEV/DontBeLazy.cursor/rules/zh-patterns.mdc · 6 | Cursor rules | api | 30/100 | 3 days ago | |
| ThanhTrunggDEV/DontBeLazy.agent/AGENTS.md · 6 | AGENTS.md | buildteststylearch+4 | 77/100 | 3 days ago | |
| ThanhTrunggDEV/DontBeLazy.cursor/AGENTS.md · 6 | AGENTS.md | buildteststylearch+4 | 77/100 | 3 days ago | |
| ThanhTrunggDEV/DontBeLazy.cursor/rules/common-agents.mdc · 6 | Cursor rules | agent-behaviour | 50/100 | 3 days ago | |
| ThanhTrunggDEV/DontBeLazy.cursor/rules/common-code-review.mdc · 6 | Cursor rules | styletesting-strategygitsecurity+3 | 65/100 | 3 days ago | |
| ThanhTrunggDEV/DontBeLazy.cursor/rules/common-coding-style.mdc · 6 | Cursor rules | style | 54/100 | 3 days ago | |
| ThanhTrunggDEV/DontBeLazy.cursor/rules/common-development-workflow.mdc · 6 | Cursor rules | gitagent-behaviour | 39/100 | 3 days ago | |
| ThanhTrunggDEV/DontBeLazy.cursor/rules/common-git-workflow.mdc · 6 | Cursor rules | lint-formatgitagent-behaviour | 43/100 | 3 days ago | |
| ThanhTrunggDEV/DontBeLazy.cursor/rules/common-hooks.mdc · 6 | Cursor rules | styletypessecuritydo-not | 36/100 | 3 days ago | |
| ThanhTrunggDEV/DontBeLazy.cursor/rules/common-patterns.mdc · 6 | Cursor rules | lint-formatstyleapi | 52/100 | 3 days ago | |
| ThanhTrunggDEV/DontBeLazy.cursor/rules/common-performance.mdc · 6 | Cursor rules | buildperformance | 48/100 | 3 days ago | |
| ThanhTrunggDEV/DontBeLazy.cursor/rules/common-security.mdc · 6 | Cursor rules | security | 39/100 | 3 days ago | |
| ThanhTrunggDEV/DontBeLazy.cursor/rules/common-testing.mdc · 6 | Cursor rules | testtesting-strategyagent-behaviour | 34/100 | 3 days ago | |
| ThanhTrunggDEV/DontBeLazy.cursor/rules/cpp-coding-style.mdc · 6 | Cursor rules | lint-formatstyle | 52/100 | 3 days ago | |
| ThanhTrunggDEV/DontBeLazy.cursor/rules/cpp-hooks.mdc · 6 | Cursor rules | buildlint-formatdeployment | 60/100 | 3 days ago | |
| ThanhTrunggDEV/DontBeLazy.cursor/rules/cpp-patterns.mdc · 6 | Cursor rules | style | 54/100 | 3 days ago | |
| ThanhTrunggDEV/DontBeLazy.cursor/rules/cpp-security.mdc · 6 | Cursor rules | securityperformancedo-not | 73/100 | 3 days ago | |
| ThanhTrunggDEV/DontBeLazy.cursor/rules/cpp-testing.mdc · 6 | Cursor rules | testtesting-strategy | 55/100 | 3 days ago | |
| ThanhTrunggDEV/DontBeLazy.cursor/rules/csharp-coding-style.mdc · 6 | Cursor rules | lint-formatstyletypes | 66/100 | 3 days ago |
Diff against .cursor/rules/zh-agents.mdc Diff against .cursor/rules/zh-patterns.mdc Diff against .agent/AGENTS.md Diff against .cursor/AGENTS.md Diff against .cursor/rules/common-agents.mdc Diff against .cursor/rules/common-code-review.mdc Diff against .cursor/rules/common-coding-style.mdc Diff against .cursor/rules/common-development-workflow.mdc Diff against .cursor/rules/common-git-workflow.mdc Diff against .cursor/rules/common-hooks.mdc Diff against .cursor/rules/common-patterns.mdc Diff against .cursor/rules/common-performance.mdc Diff against .cursor/rules/common-security.mdc Diff against .cursor/rules/common-testing.mdc Diff against .cursor/rules/cpp-coding-style.mdc Diff against .cursor/rules/cpp-hooks.mdc Diff against .cursor/rules/cpp-patterns.mdc Diff against .cursor/rules/cpp-security.mdc Diff against .cursor/rules/cpp-testing.mdc Diff against .cursor/rules/csharp-coding-style.mdc
Similar configs
Same format, overlapping stack, ranked by quality.
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| hiromaily/go-crypto-wallet.cursor/rules/typescript.mdc · 126 | Cursor rules | setupbuildtestlint-format+6 | 100/100 | 3 days ago | |
| TechSquidTV/Hermes.cursor/rules/10-hermes-api.mdc · 45 | Cursor rules | testlint-formatstylearch+5 | 100/100 | 3 days ago | |
| markstev/mark-starter.cursor/rules/frontend.mdc · 0 | Cursor rules | setuptestlint-formatstyle+6 | 99/100 | 3 days ago | |
| Allymahmoud/case-intake-platform.cursor/rules/frontend.mdc · 0 | Cursor rules | setuptestlint-formatstyle+7 | 99/100 | 3 days ago | |
| deifos/clipmira-subtitles.cursor/rules/frontend.mdc · 1 | Cursor rules | setuptestlint-formatstyle+7 | 99/100 | 3 days ago | |
| dodgecfr/combatfilms-webapp.cursor/rules/frontend.mdc · 0 | Cursor rules | setuptestlint-formatstyle+7 | 99/100 | 3 days ago | |
| langflow-ai/langflow.cursor/rules/docs_development.mdc · 153k | Cursor rules | setupbuildtestlint-format+7 | 97/100 | 3 days ago | |
| TechSquidTV/Hermes.cursor/rules/20-hermes-api-tests.mdc · 45 | Cursor rules | teststyletesting-strategysecurity+3 | 97/100 | 3 days ago |
