Skip to content
cccskills
FreePublished on GitHub

rust-core

Use when writing, reviewing, or refactoring Rust code. Covers ownership, borrowing, error handling, async patterns, API design, memory optimization, performance, testing, and common anti-patterns. Targets Rust 1.80+ and Edition 2024. Invoke with /rust-core.

The English summary is being prepared. Showing the original description.

See how to install

Files included (16)

  • SKILL.md20.0 KB
  • references/compiler-errors.md1.6 KB
  • rules/anti-patterns.md46.7 KB
  • rules/api-design.md59.7 KB
  • rules/async.md63.6 KB
  • rules/documentation.md35.6 KB
  • rules/error-handling.md44.1 KB
  • rules/lint.md32.6 KB
  • rules/memory.md55.5 KB
  • rules/naming.md41.5 KB
  • rules/optimization.md45.0 KB
  • rules/ownership.md34.8 KB
  • rules/performance.md35.7 KB
  • rules/project-layout.md34.1 KB
  • rules/testing.md52.6 KB
  • rules/types.md33.5 KB

SKILL.md (original)

Review the instructions the agent will receive before you install.

Rust Core

Comprehensive guide for writing high-quality, idiomatic, and optimized Rust code. Targets Rust 1.80+ and Edition 2024.

When to Apply

  • Writing new Rust functions, structs, or modules
  • Implementing error handling or async code
  • Designing public APIs for libraries
  • Reviewing code for ownership/borrowing issues
  • Optimizing memory usage or reducing allocations
  • Tuning performance for hot paths
  • Refactoring existing Rust code
  • Fixing compiler errors (see references/compiler-errors.md)

Edition 2024 Changes (Rust 1.85+)

ChangeImpactAction
unsafe blocks required for extern blocksextern "C" { ... } now needs unsafe { extern "C" { ... } }Wrap extern blocks in unsafe
unsafe_op_in_unsafe_fn lintunsafe fn body requires explicit unsafe blocks for unsafe opsAdd unsafe { ... } inside unsafe fns
if let temporary scopeTemporaries dropped at end of if let blockMay extend borrow lifetimes
gen keyword reservedgen { ... } blocks for iteratorsUse gen for lazy iterators
#[diagnostic::on_unimplemented]Better error messages for trait failuresAdd to library traits
Nested or-patternsSome(1 | 2) stabilizedUse in match arms

Run cargo fix --edition to apply most changes automatically.

Rule Categories by Priority

PriorityCategoryPrefixRules
1Ownership & Borrowingown-12
2Error Handlingerr-12
3Memory Optimizationmem-15
4API Designapi-15
5Async/Awaitasync-15
6Compiler Optimizationopt-12
7Naming Conventionsname-16
8Type Safetytype-10
9Testingtest-13
10Documentationdoc-11
11Performance Patternsperf-11
12Project Structureproj-11
13Clippy & Lintinglint-11
14Anti-patternsanti-15

Detailed rules live in rules/ — 14 files, one per prefix group (ownership.md covers own-, error-handling.md covers err-, …). Each ## <rule-id> section inside a category file is one rule, so a grep for a rule id lands directly on it.

Rule Index

Ownership & Borrowing (own-)

RuleDescription
own-borrow-over-clonePrefer &T borrowing over .clone()
own-slice-over-vecAccept &[T] not &Vec<T>, &str not &String
own-cow-conditionalUse Cow<'a, T> for conditional ownership
own-arc-sharedUse Arc<T> for thread-safe shared ownership
own-rc-single-threadUse Rc<T> for single-threaded sharing
own-refcell-interiorUse RefCell<T> for interior mutability (single-thread)
own-mutex-interiorUse Mutex<T> for interior mutability (multi-thread)
own-rwlock-readersUse RwLock<T> when reads dominate writes
own-copy-smallDerive Copy for small, trivial types
own-clone-explicitMake Clone explicit, avoid implicit copies
own-move-largeMove large data instead of cloning
own-lifetime-elisionRely on lifetime elision when possible

Error Handling (err-)

RuleDescription
err-thiserror-libUse thiserror for library error types
err-anyhow-appUse anyhow for application error handling
err-result-over-panicReturn Result, don't panic on expected errors
err-context-chainAdd context with .context() or .with_context()
err-no-unwrap-prodNever use .unwrap() in production code
err-expect-bugs-onlyUse .expect() only for programming errors
err-question-markUse ? operator for clean propagation
err-from-implUse #[from] for automatic error conversion
err-source-chainUse #[source] to chain underlying errors
err-lowercase-msgError messages: lowercase, no trailing punctuation
err-doc-errorsDocument errors with # Errors section
err-custom-typeCreate custom error types, not Box<dyn Error>

Memory Optimization (mem-)

RuleDescription
mem-with-capacityUse with_capacity() when size is known
mem-smallvecUse SmallVec for usually-small collections
mem-arrayvecUse ArrayVec for bounded-size collections
mem-box-large-variantBox large enum variants to reduce type size
mem-boxed-sliceUse Box<[T]> instead of Vec<T> when fixed
mem-thinvecUse ThinVec for often-empty vectors
mem-clone-fromUse clone_from() to reuse allocations
mem-reuse-collectionsReuse collections with clear() in loops
mem-avoid-formatAvoid format!() when string literals work
mem-write-over-formatUse write!() instead of format!()
mem-arena-allocatorUse arena allocators for batch allocations
mem-zero-copyUse zero-copy patterns with slices and Bytes
mem-compact-stringUse CompactString for small string optimization
mem-smaller-integersUse smallest integer type that fits
mem-assert-type-sizeAssert hot type sizes to prevent regressions

API Design (api-)

RuleDescription
api-builder-patternUse Builder pattern for complex construction
api-builder-must-useAdd #[must_use] to builder types
api-newtype-safetyUse newtypes for type-safe distinctions
api-typestateUse typestate for compile-time state machines
api-sealed-traitSeal traits to prevent external implementations
api-extension-traitUse extension traits to add methods to foreign types
api-parse-dont-validateParse into validated types at boundaries
api-impl-intoAccept impl Into<T> for flexible string inputs
api-impl-asrefAccept impl AsRef<T> for borrowed inputs
api-must-useAdd #[must_use] to Result-returning functions
api-non-exhaustiveUse #[non_exhaustive] for future-proof enums/structs
api-from-not-intoImplement From, not Into (auto-derived)
api-default-implImplement Default for sensible defaults
api-common-traitsImplement Debug, Clone, PartialEq eagerly
api-serde-optionalGate Serialize/Deserialize behind feature flag

Async/Await (async-)

RuleDescription
async-tokio-runtimeUse Tokio for production async runtime
async-no-lock-awaitNever hold Mutex/RwLock across .await
async-spawn-blockingUse spawn_blocking for CPU-intensive work
async-tokio-fsUse tokio::fs not std::fs in async code
async-cancellation-tokenUse CancellationToken for graceful shutdown
async-join-parallelUse tokio::join! for parallel operations
async-try-joinUse tokio::try_join! for fallible parallel ops
async-select-racingUse tokio::select! for racing/timeouts
async-bounded-channelUse bounded channels for backpressure
async-mpsc-queueUse mpsc for work queues
async-broadcast-pubsubUse broadcast for pub/sub patterns
async-watch-latestUse watch for latest-value sharing
async-oneshot-responseUse oneshot for request/response
async-joinset-structuredUse JoinSet for dynamic task groups
async-clone-before-awaitClone data before await, release locks

Compiler Optimization (opt-)

RuleDescription
opt-inline-smallUse #[inline] for small hot functions
opt-inline-always-rareUse #[inline(always)] sparingly
opt-inline-never-coldUse #[inline(never)] for cold paths
opt-cold-unlikelyUse #[cold] for error/unlikely paths
opt-likely-hintUse likely()/unlikely() for branch hints
opt-lto-releaseEnable LTO in release builds
opt-codegen-unitsUse codegen-units = 1 for max optimization
opt-pgo-profileUse PGO for production builds
opt-target-cpuSet target-cpu=native for local builds
opt-bounds-checkUse iterators to avoid bounds checks
opt-simd-portableUse portable SIMD for data-parallel ops
opt-cache-friendlyDesign cache-friendly data layouts (SoA)

Naming Conventions (name-)

RuleDescription
name-types-camelUse UpperCamelCase for types, traits, enums
name-variants-camelUse UpperCamelCase for enum variants
name-funcs-snakeUse snake_case for functions, methods, modules
name-consts-screamingUse SCREAMING_SNAKE_CASE for constants/statics
name-lifetime-shortUse short lowercase lifetimes: 'a, 'de, 'src
name-type-param-singleUse single uppercase for type params: T, E, K, V
name-as-freeas_ prefix: free reference conversion
name-to-expensiveto_ prefix: expensive conversion
name-into-ownershipinto_ prefix: ownership transfer
name-no-get-prefixNo get_ prefix for simple getters
name-is-has-boolUse is_, has_, can_ for boolean methods
name-iter-conventionUse iter/iter_mut/into_iter for iterators
name-iter-methodName iterator methods consistently
name-iter-type-matchIterator type names match method
name-acronym-wordTreat acronyms as words: Uuid not UUID
name-crate-no-rsCrate names: no -rs suffix

Type Safety (type-)

RuleDescription
type-newtype-idsWrap IDs in newtypes: UserId(u64)
type-newtype-validatedNewtypes for validated data: Email, Url
type-enum-statesUse enums for mutually exclusive states
type-option-nullableUse Option<T> for nullable values
type-result-fallibleUse Result<T, E> for fallible operations
type-phantom-markerUse PhantomData<T> for type-level markers
type-never-divergeUse ! type for functions that never return
type-generic-boundsAdd trait bounds only where needed
type-no-stringlyAvoid stringly-typed APIs, use enums/newtypes
type-repr-transparentUse #[repr(transparent)] for FFI newtypes

Testing (test-)

RuleDescription
test-cfg-test-moduleUse #[cfg(test)] mod tests { }
test-use-superUse use super::*; in test modules
test-integration-dirPut integration tests in tests/ directory
test-descriptive-namesUse descriptive test names
test-arrange-act-assertStructure tests as arrange/act/assert
test-proptest-propertiesUse proptest for property-based testing
test-mockall-mockingUse mockall for trait mocking
test-mock-traitsUse traits for dependencies to enable mocking
test-fixture-raiiUse RAII pattern (Drop) for test cleanup
test-tokio-asyncUse #[tokio::test] for async tests
test-should-panicUse #[should_panic] for panic tests
test-criterion-benchUse criterion for benchmarking
test-doctest-examplesKeep doc examples as executable tests
test-mutation-assertionsUse mutation testing to verify test assertions
test-mutation-trustworthinessMake mutation runs trustworthy and affordable

Documentation (doc-)

RuleDescription
doc-all-publicDocument all public items with ///
doc-module-innerUse //! for module-level documentation
doc-examples-sectionInclude # Examples with runnable code
doc-errors-sectionInclude # Errors for fallible functions
doc-panics-sectionInclude # Panics for panicking functions
doc-safety-sectionInclude # Safety for unsafe functions
doc-question-markUse ? in examples, not .unwrap()
doc-hidden-setupUse # prefix to hide example setup code
doc-intra-linksUse intra-doc links: [Vec]
doc-link-typesLink related types and functions in docs
doc-cargo-metadataFill Cargo.toml metadata

Performance Patterns (perf-)

RuleDescription
perf-iter-over-indexPrefer iterators over manual indexing
perf-iter-lazyKeep iterators lazy, collect() only when needed
perf-collect-onceDon't collect() intermediate iterators
perf-entry-apiUse entry() API for map insert-or-update
perf-drain-reuseUse drain() to reuse allocations
perf-extend-batchUse extend() for batch insertions
perf-chain-avoidAvoid chain() in hot loops
perf-collect-intoUse collect_into() for reusing containers
perf-black-box-benchUse black_box() in benchmarks
perf-release-profileOptimize release profile settings
perf-profile-firstProfile before optimizing

Project Structure (proj-)

RuleDescription
proj-lib-main-splitKeep main.rs minimal, logic in lib.rs
proj-mod-by-featureOrganize modules by feature, not type
proj-flat-smallKeep small projects flat
proj-mod-rs-dirUse mod.rs for multi-file modules
proj-pub-crate-internalUse pub(crate) for internal APIs
proj-pub-super-parentUse pub(super) for parent-only visibility
proj-pub-use-reexportUse pub use for clean public API
proj-prelude-moduleCreate prelude module for common imports
proj-bin-dirPut multiple binaries in src/bin/
proj-workspace-largeUse workspaces for large projects
proj-workspace-depsUse workspace dependency inheritance

Clippy & Linting (lint-)

RuleDescription
lint-deny-correctness#![deny(clippy::correctness)]
lint-warn-suspicious#![warn(clippy::suspicious)]
lint-warn-style#![warn(clippy::style)]
lint-warn-complexity#![warn(clippy::complexity)]
lint-warn-perf#![warn(clippy::perf)]
lint-pedantic-selectiveEnable clippy::pedantic selectively
lint-missing-docs#![warn(missing_docs)]
lint-unsafe-doc#![warn(clippy::undocumented_unsafe_blocks)]
lint-cargo-metadata#![warn(clippy::cargo)] for published crates
lint-rustfmt-checkRun cargo fmt --check in CI
lint-workspace-lintsConfigure lints at workspace level

Anti-patterns (anti-)

RuleDescription
anti-unwrap-abuseDon't use .unwrap() in production code
anti-expect-lazyDon't use .expect() for recoverable errors
anti-clone-excessiveDon't clone when borrowing works
anti-lock-across-awaitDon't hold locks across .await
anti-string-for-strDon't accept &String when &str works
anti-vec-for-sliceDon't accept &Vec<T> when &[T] works
anti-index-over-iterDon't use indexing when iterators work
anti-panic-expectedDon't panic on expected/recoverable errors
anti-empty-catchDon't use empty if let Err(_) = ... blocks
anti-over-abstractionDon't over-abstract with excessive generics
anti-premature-optimizeDon't optimize before profiling
anti-type-erasureDon't use Box<dyn Trait> when impl Trait works
anti-format-hot-pathDon't use format!() in hot paths
anti-collect-intermediateDon't collect() intermediate iterators
anti-stringly-typedDon't use strings for structured data

Ownership & Borrowing

  • Prefer &T borrowing over .clone()
  • Accept &[T] not &Vec<T>, &str not &String
  • Use Cow<'a, T> for conditional ownership
  • Use Arc<T> for thread-safe shared ownership, Rc<T> for single-threaded
  • Use RefCell<T> (single-thread) or Mutex<T>/RwLock<T> (multi-thread) for interior mutability
  • Derive Copy for small, trivial types
  • Move large data instead of cloning
  • Rely on lifetime elision when possible

Error Handling

  • Use thiserror for library error types, anyhow for application error handling
  • Return Result, don't panic on expected errors
  • Add context with .context() or .with_context()
  • Never use .unwrap() in production code
  • Use .expect() only for programming errors
  • Use ? operator for clean propagation
  • Use #[from] for automatic error conversion
  • Use #[source] to chain underlying errors
  • Error messages: lowercase, no trailing punctuation
  • Document errors with # Errors section
  • Create custom error types, not Box<dyn Error>

Memory Optimization

  • Use with_capacity() when size is known
  • Use SmallVec for usually-small collections, ArrayVec for bounded-size
  • Box large enum variants to reduce type size
  • Use Box<[T]> instead of Vec<T> when fixed size
  • Use clone_from() to reuse allocations
  • Reuse collections with clear() in loops
  • Avoid format!() when string literals work; use write!() instead
  • Use smallest integer type that fits
  • Assert hot type sizes to prevent regressions

API Design

  • Use Builder pattern for complex construction; add #[must_use] to builder types
  • Use newtypes for type-safe distinctions (UserId(u64), Email, Url)
  • Use typestate for compile-time state machines
  • Seal traits to prevent external implementations when appropriate
  • Use extension traits to add methods to foreign types
  • Parse into validated types at boundaries
  • Accept impl Into<T> for flexible string inputs, impl AsRef<T> for borrowed inputs
  • Add #[must_use] to Result-returning functions
  • Use #[non_exhaustive] for future-proof enums/structs
  • Implement From, not Into (auto-derived)
  • Implement Default for sensible defaults
  • Implement Debug, Clone, PartialEq eagerly
  • Gate Serialize/Deserialize behind feature flag

Async/Await

  • Use Tokio for production async runtime
  • Never hold Mutex/RwLock across .await
  • Use spawn_blocking for CPU-intensive work
  • Use tokio::fs not std::fs in async code
  • Use CancellationToken for graceful shutdown
  • Use tokio::join! for parallel operations, tokio::try_join! for fallible
  • Use tokio::select! for racing/timeouts
  • Use bounded channels for backpressure
  • Use JoinSet for dynamic task groups
  • Clone data before await, release locks

Testing

  • Use #[cfg(test)] mod tests { } with use super::*;
  • Put integration tests in tests/ directory
  • Structure tests as arrange/act/assert
  • Use #[tokio::test] for async tests
  • Use proptest for property-based testing
  • Use mockall for trait mocking; design dependencies as traits
  • Use RAII pattern (Drop) for test cleanup
  • Use criterion for benchmarking
  • Keep doc examples as executable tests
  • Use #[should_panic] for panic tests
  • Aim for 80%+ coverage; test edge cases and error paths

Anti-Patterns

The 15 anti-* rules are indexed in the Rule Index above with full rationale and ❌/✅ examples in rules/anti-patterns.md.

Essential Commands

cargo build --release    # Build with optimizations
cargo test                # Run all tests
cargo test -- --nocapture # Run tests with output
cargo clippy -- -D warnings  # Lint with warnings as errors
cargo fmt --check         # Check formatting
cargo doc --no-deps       # Generate documentation
cargo bench               # Run benchmarks
cargo fix --edition       # Auto-fix edition migration

Cargo.toml Release Profile

[profile.release]
opt-level = 3
lto = "fat"
codegen-units = 1
panic = "abort"
strip = true

[profile.dev.package."*"]
opt-level = 3

References

  • rules/ — 14 category files (179 rules total), one file per prefix group, read on demand
  • references/compiler-errors.md — Compiler error quick reference (E0382, E0502, E0716, etc.)

Reviews

No reviews yet. Tell others what you thought.

Comments

No login needed. Share how it worked for you, ask a question, or note where it did not run.

No comments yet. Be the first to write one.

Comments are published right away. Do not include personal information such as email addresses or phone numbers. Up to 2 URLs.

0 / 1,000 characters

This form is protected by reCAPTCHA, and the Google Privacy Policy and Terms of Service apply.

More skills from this repository

Use when building Python async HTTP services or clients with aiohttp - web server routing, middleware, WebSocket, SSE, streaming, client sessions, pytest-aiohttp testing, or troubleshooting SSL and timeout issues

The English summary is being prepared. Showing the original description.

CodeAtCode/oss-ai-skills24Updated Oct 9, 2026

Use when doing structural code search and rewriting - ast-grep linting, refactoring, multi-language patterns

The English summary is being prepared. Showing the original description.

CodeAtCode/oss-ai-skills24Updated Oct 9, 2026

Use when building GBA games with the BPCore Lua engine - entity, sprite and tilemap functions, SRAM save and load, link cable multiplayer protocol, camera and scrolling, or optimization patterns

The English summary is being prepared. Showing the original description.

CodeAtCode/oss-ai-skills24Updated Oct 9, 2026

celery

Free

Use when running background tasks with Celery - worker and broker configuration (Redis, RabbitMQ), task routing by name vs queue, chains/groups/chords, retry patterns (autoretry_for, retry_backoff), acks_late semantics, failure detection, and monitoring with Flower

The English summary is being prepared. Showing the original description.

CodeAtCode/oss-ai-skills24Updated Oct 9, 2026

django

Free

Use when building Django applications - security hardening, authentication and permissions, ORM optimization, PostgreSQL features, Django 6.0, migrations, testing, and ecosystem libraries

The English summary is being prepared. Showing the original description.

CodeAtCode/oss-ai-skills24Updated Oct 9, 2026

Use when customizing Django Admin - save_formset, get_search_results, formsets, queryset optimization, db_index, custom URLs

The English summary is being prepared. Showing the original description.

CodeAtCode/oss-ai-skills24Updated Oct 9, 2026

See all skills by CodeAtCode

Report a problem with this skill