Rust ownership and borrowing patterns: borrowed parameters, deliberate clones, Rc vs Arc, Cow, and when lifetime annotations are needed.
.cursor/rules/rust-ownership-patterns.mdc. Downloaded files need to be placed in that repository path.---
description: "Rust ownership and borrowing patterns: borrowed parameters, deliberate clones, Rc vs Arc, Cow, and when lifetime annotations are needed."
globs: "**/*"
alwaysApply: false
---
Apply these rules when designing Rust functions and data structures.
## Parameters and return values
- Take borrowed, general parameter types: `&str` instead of `&String`, `&[T]` instead of `&Vec<T>`, `&Path`/`impl AsRef<Path>` for paths.
- Take ownership (`String`, `Vec<T>`) when the function stores the value; constructors can accept `impl Into<String>` so callers pass either `&str` or `String`.
- Return owned values from functions that create data; return references only when they point into an argument.
## Moves and clones
- Assigning or passing a non-`Copy` value moves it. If you need it afterwards, borrow instead, or clone deliberately.
- Clone only when two owners are needed. In loops and hot paths, check whether a borrow, `std::mem::take`, or an index would avoid the clone.
- Derive `Clone` (and `Copy` for small plain data) when callers reasonably need copies.
## Lifetimes
- Rely on lifetime elision for the common cases (one input reference, or `&self` methods). Add explicit lifetimes when a function returns a reference derived from one of several inputs, or a struct stores a reference.
- If a struct needs a lifetime parameter only to avoid a clone, consider owning the data instead; borrowed structs make APIs harder to use.
## Shared ownership
- `Rc<T>` for shared ownership within one thread, `Arc<T>` across threads. Add `RefCell`/`Mutex` only if the shared value must change, and use `Weak` for back-references.
## Cow
- Use `Cow<'_, str>` (or `Cow<'_, [T]>`) when a function usually returns its input unchanged but sometimes must allocate:
```rust
use std::borrow::Cow;
fn normalize_newlines(input: &str) -> Cow<'_, str> {
if input.contains("\r\n") {
Cow::Owned(input.replace("\r\n", "\n"))
} else {
Cow::Borrowed(input)
}
}
```
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
language
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A parser API takes &String and Vec<Token> by value, clones the input for each token, and stores &str slices in a struct with a lifetime that leaks into every caller.
Using the Rust Ownership Patterns rule, propose a better signature set for src/parser.rs.
Functions take &str/&[Token]; per-token clones are removed or justified; the stored-reference struct either keeps one clear lifetime or owns its strings with the trade-off explained; Cow is used where input is usually returned unchanged.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/rust-ownership-patterns.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "Rust Ownership Patterns project conventions"
globs: "**/*"
alwaysApply: false
---
Apply these rules when designing Rust functions and data structures.
## Parameters and return values
- Take borrowed, general parameter types: `&str` instead of `&String`, `&[T]` instead of `&Vec<T>`, `&Path`/`impl AsRef<Path>` for paths.
- Take ownership (`String`, `Vec<T>`) when the function stores the value; constructors can accept `impl Into<String>` so callers pass either `&str` or `String`.
- Return owned values from functions that create data; return references only when they point into an argument.
## Moves and clones
- Assigning or passing a non-`Copy` value moves it. If you need it afterwards, borrow instead, or clone deliberately.
- Clone only when two owners are needed. In loops and hot paths, check whether a borrow, `std::mem::take`, or an index would avoid the clone.
- Derive `Clone` (and `Copy` for small plain data) when callers reasonably need copies.
## Lifetimes
- Rely on lifetime elision for the common cases (one input reference, or `&self` methods). Add explicit lifetimes when a function returns a reference derived from one of several inputs, or a struct stores a reference.
- If a struct needs a lifetime parameter only to avoid a clone, consider owning the data instead; borrowed structs make APIs harder to use.
## Shared ownership
- `Rc<T>` for shared ownership within one thread, `Arc<T>` across threads. Add `RefCell`/`Mutex` only if the shared value must change, and use `Weak` for back-references.
## Cow
- Use `Cow<'_, str>` (or `Cow<'_, [T]>`) when a function usually returns its input unchanged but sometimes must allocate:
```rust
use std::borrow::Cow;
fn normalize_newlines(input: &str) -> Cow<'_, str> {
if input.contains("\r\n") {
Cow::Owned(input.replace("\r\n", "\n"))
} else {
Cow::Borrowed(input)
}
}
```
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.