一键导入
Rust-Claude-Skill-Package
Rust-Claude-Skill-Package 收录了来自 Impertio-Studio 的 44 个 skills,并提供仓库级职业覆盖和站内 skill 详情页。
这个仓库中的 skills
Use when starting any Rust task to route to the correct rust-* skill, and when finishing any Rust task to run the cross-skill quality checklist (clippy, rustfmt, MSRV, edition idioms, error handling, async hygiene, doc coverage). Prevents loading the wrong skill, missing a relevant skill, and shipping Rust code that fails clippy or ignores the project MSRV. Covers: a routing table mapping user-prompt patterns to rust-* skills (ownership question to rust-syntax-ownership, lifetime error to rust-errors-lifetimes, async runtime question to rust-impl-async-tokio, etc.), and a cross-skill quality checklist every Rust task should pass before completion. Keywords: "which Rust skill", "Rust task routing", "Rust code review checklist", "rust quality gate", clippy, rustfmt, MSRV, "Rust best practice check", "Rust code quality", "before I ship Rust", orchestrator, "Rust skill index", "what skill for", routing, "Rust checklist".
Use when the user asks about Rust editions (2015/2018/2021/2024), MSRV, the version matrix, channels (stable/beta/nightly), what stabilized in which release, or how Rust evolves. Prevents writing pre-2024 idioms in edition-2024 code, recommending unstabilised features, or mismatching `rust-version` with required features. Covers: edition system, stability commitment, MSRV-aware resolver (1.84), channel model, Rust 1.65 to 1.87 stabilizations (GATs, AFIT/RPITIT, LazyLock, precise capturing, edition 2024 stable, trait upcasting, asm! jumps), `cargo fix --edition` migration. Keywords: edition 2024, MSRV, rust-version, version matrix, what version added X, when did Y stabilize, cargo fix edition, channel stable beta nightly, rustup toolchain, "which Rust version", "what's new", semver, no-breakage guarantee, GATs 1.65, AFIT 1.75, RPITIT, async closures, trait upcasting 1.86, precise capturing 1.87, strict provenance 1.84, MSRV resolver, "how do I upgrade", "should I bump edition", "what changed".
Use when the user needs to understand Rust's type system fundamentals: nominal typing, zero-sized types, repr attributes, niche optimization, primitive types, the never type, type-state pattern, or const generics. Prevents misusing repr(C) when default repr suffices, packing types unsafely, assuming structural typing, or surprises with edition-2024 never-type fallback. Covers: nominal vs structural, ZST + PhantomData, repr (Rust/C/transparent/packed/align), niche optimization (NonZero, Option<NonNull>), primitives (integers/floats/bool/char/unit), never type `!` and edition-2024 fallback change, type-state pattern, const generics overview. Keywords: type system, nominal typing, zero-sized type, ZST, PhantomData, repr C, repr transparent, repr packed, niche optimization, NonZero, never type, "!", bottom type, divergence, type state, const generics, primitive types, "what is unit", "how big is", layout, alignment, "Option<NonZeroU32> size", "what is a tag", edition 2024 fallback.
Use when the user needs Generic Associated Types: `type Item<'a>` in a trait, the `LendingIterator` pattern, callback registries parameterised by lifetime, or families of types whose lifetime/type varies per call. Prevents reaching for higher-kinded-type work-arounds that have been obsolete since 1.65, missing required `where` clauses on GAT bounds, or confusing GATs with regular associated types. Covers: GAT syntax (`type Item<'a>` in trait + impl), lifetime GATs, the `LendingIterator` family, callback registries, type-parameter-by-lifetime patterns, GAT bound requirements (`where Self: 'a`). Keywords: GAT, "generic associated type", "type Item<'a>", "LendingIterator", "where Self: 'a", "associated type with lifetime", "associated type with generic", "lifetime in associated type", "stream of borrows", "self-borrow", "higher-kinded type Rust", "1.65 stabilization", lifetime GAT, type GAT.
Use when the user writes a `match`, `if let`, `let else`, `while let`, an if-let chain (edition 2024 stable in 1.88), destructures a struct/tuple/enum/slice/reference, uses `ref` / `ref mut`, guards, or or-patterns. Prevents non-exhaustive `match` on enums, missing the if-let chain idiom, accidentally moving instead of borrowing in match arms, and forgetting that `let else` requires the else branch to diverge. Covers: `match` exhaustiveness, arm order, wildcards `_`, `if let` and `if let else` chains, `let else` (1.65), `while let`, destructuring (tuple/struct/enum/slice/reference), `ref` and `ref mut`, or-patterns (`A | B`), guards (`if cond`), bindings (`name @ pattern`), `..` rest pattern, range patterns, literal patterns. Keywords: match, "if let", "let else", "while let", pattern, destructuring, ref, "ref mut", "or-pattern", "match guard", "match arm", exhaustiveness, "non-exhaustive", wildcard, "_", "@ binding", ".. rest pattern", "if let chain", "range pattern", "or pattern", "what is ref", "how to des
Use when iterating on rustc compile errors: how to read a rustc error, which errors to fix first, when to apply rustc's suggestion blindly vs inspect it, when to consult `rustc --explain`, and when to stop and ask instead of cascading edits. Prevents fixing errors bottom-up, blindly accepting lifetime suggestions, and cascading clone()/lifetime edits that mask a design problem. Covers: reading a rustc error (primary span, secondary spans, help, note), fix earliest error first (later errors are often cascades), `cargo fix` for machine-applicable suggestions, when to inspect a suggestion (lifetime / trait-bound suggestions need judgement), `rustc --explain EXXXX`, one-line fixes (missing `mut` / `&` / `use` / derive), common refactors (introduce binding, take by-value, restructure ownership), and when to STOP and ask the user (ownership refactor cascading across modules, lifetime requiring API redesign). Keywords: "rustc error", "compile error", "fix compile error", "cargo fix", "rustc --explain", "how to read
Use when reviewing Rust code for quality: clippy lint categories, naming idioms, error-handling hygiene, async correctness, memory-pattern appropriateness, and justified lint suppressions. Prevents approving code with unjustified `.unwrap()`, `.await` inside a held lock, Arc<Mutex> where an atomic fits, or `#[allow]` without a reason. Covers: clippy lint categories (correctness deny, suspicious / style / complexity / perf warn, pedantic / nursery / restriction allow), API-guidelines naming idioms (snake_case fn/var, CamelCase type/trait, SCREAMING_CASE const), error-handling review (every unwrap/expect must be justified), async review (no await inside lock, no blocking in async, Send-across-await), memory review (Arc<Mutex> vs atomic vs RwLock, RefCell single-thread only), reviewing which `#[allow]` are justified. Keywords: "code review Rust", "review Rust code", clippy, "lint categories", "clippy correctness", "clippy pedantic", "naming convention", snake_case, CamelCase, "API guidelines", "unwrap review", "
Use when the user chooses an error-handling crate: `thiserror` for structured library errors, `anyhow` for opaque application errors, both together, or migrates between them. Prevents using anyhow in a public library API, using thiserror where a one-off opaque error suffices, and losing the error source chain. Covers: when to use thiserror (library, structured, callers match on variants) vs anyhow (application, opaque, callers display), thiserror derive (`#[derive(Error)]`, `#[error("...")]`, `#[from]`, `#[source]`, `#[transparent]`), anyhow API (`anyhow::Result`, `Context` trait `.context()` / `.with_context()`, `bail!`, `ensure!`, `anyhow!`), `Error::downcast_ref` for recovering concrete types, combining thiserror at library boundary with anyhow at the app boundary, migration paths. Keywords: thiserror, anyhow, "#[derive(Error)]", "#[error(...)]", "#[from]", "#[source]", "#[transparent]", "anyhow::Result", Context, ".context()", ".with_context()", "bail!", "ensure!", "anyhow!", downcast_ref, "library error"
Use when a Rust program panics at runtime: index out of bounds, unwrap on None / Err, integer overflow, division by zero, or the user must choose panic = "unwind" vs "abort", read a backtrace, or guard an FFI boundary with catch_unwind. Prevents shipping `.unwrap()` on fallible paths, relying on unwind across an FFI boundary, and being surprised that release builds wrap integer overflow. Covers: panic mechanics (panic! macro, unwind vs abort, drop during unwind), RUST_BACKTRACE=1 / full, debug-assertions (on in dev, off in release), integer overflow (panics in dev, wraps in release, overflow-checks override), division by zero, slice index out of bounds vs `.get()`, panic = "abort" profile tradeoffs, catch_unwind for FFI, process::abort vs process::exit. Keywords: panic, "thread panicked", "index out of bounds", "called unwrap on", "unwrap on None", "unwrap on Err", "attempt to add with overflow", "integer overflow", "divide by zero", "attempt to divide by zero", RUST_BACKTRACE, backtrace, "unwind", "abort", "
Use when the user hits linker errors ("linker `cc` not found", "undefined reference to", "could not find native static library"), duplicate-symbol errors from multiple major versions in the dependency tree, MSRV mismatches, or surprising feature-unification behavior. Prevents blind `cargo clean`, ignoring `cargo tree -d` duplicate analysis, and treating a feature-unification surprise as a compiler bug. Covers: missing linker / build-essentials per OS, "undefined reference" (missing native lib, library order, build.rs link directives), "could not find native static library" (rustc-link-search path), duplicate symbols from multiple major versions (cargo tree -d, [patch], version unification), MSRV mismatch (dependency needs newer rustc), feature unification surprises, `cargo update -p` targeted upgrades, when `cargo clean` is and is not the answer. Keywords: "linker cc not found", "linker not found", "undefined reference", "could not find native static library", "note: ld returned", "duplicate symbol", "multipl
Use when the user hits "future cannot be sent between threads safely", "future is not Send", Pin/Unpin errors, lifetime errors inside an `async fn`, "cannot move out of pinned", or AFIT dyn-dispatch problems. Prevents holding a MutexGuard or Rc across `.await`, storing a non-Unpin future on the stack wrongly, and reflexively reaching for `async_trait` when AFIT now works. Covers: Future not Send (holding non-Send across .await: MutexGuard, Rc, RefCell::Ref), cannot-move-out-of-pinned, !Unpin future on stack, lifetime errors in async fn signatures, async fn in trait dyn-dispatch limits (when async_trait crate is still needed), tokio blocking-in-async runtime panics, block_on inside a running runtime; fix patterns. Keywords: "future is not Send", "future cannot be sent between threads", "cannot be sent between threads safely", "held across an await point", "MutexGuard across await", Pin, Unpin, "cannot move out of", "not Unpin", "async lifetime", "async fn in trait", AFIT, async_trait, "block_on", "blocking the
Use when the user hits trait-related error codes E0277 / E0599 / E0220 / E0308 / E0282, gets "trait bound not satisfied", "method not found", needs a missing `use` for a trait, or wonders about the 1.84 next-generation trait solver. Prevents adding pointless bounds, missing the trait-import that brings a method into scope, and confusing inference failure with a real bound failure. Covers: E0277 trait bound not satisfied, E0599 method not found in scope, E0220 associated type not found, E0308 type mismatch (trait-related cases), E0282 type annotations needed; fix patterns (import the trait, add the bound to the generic, derive the missing trait, blanket-impl reasoning), the 1.84 opt-in next-gen trait solver and how it changes diagnostics. Keywords: E0277, E0599, E0220, E0308, E0282, "trait bound not satisfied", "method not found", "no method named", "the trait is not implemented", "associated type not found", "type annotations needed", "cannot infer type", "trait not in scope", "missing use", "new trait solver
Use when the user hits borrow-checker error codes E0382 / E0502 / E0596 / E0499 / E0500 / E0716, asks "why can't I use this after move", "why can't I have & and &mut at the same time", or needs a recipe to satisfy the borrow checker. Prevents adding `.clone()` everywhere as the universal fix, missing NLL improvements, and using RefCell to evade the rules when a refactor suffices. Covers: E0382 use of moved value, E0502 mutable+immutable borrow at same time, E0596 cannot borrow as mutable, E0500 closure borrow conflict, E0499 multiple mutable borrows, E0716 temporary value dropped while borrowed; fix patterns (clone, restructure, take(), mem::replace, split borrow, introduce intermediate binding, scope tightening via NLL). Keywords: E0382, E0502, E0596, E0499, E0500, E0716, "borrow checker", "moved value", "use of moved value", "cannot borrow as mutable", "cannot borrow as immutable while", "already mutably borrowed", "temporary value dropped", "doesn't live long enough", "borrow checker error", "fix borrow",
Use when the user hits lifetime-related error codes E0106 / E0623 / E0495 / E0700 / E0759 / E0515, or wonders why elision didn't infer their lifetime, or how the 2024 RPIT capture default broke a 2021 signature. Prevents reflexively adding `'static`, missing the `+ use<'a, T>` 2024 opt-out, or restructuring an API when adding a lifetime annotation would suffice. Covers: E0106 missing lifetime specifier, E0623 lifetime mismatch (input vs output), E0495 cannot infer appropriate lifetime, E0700 hidden type captures lifetime not in scope (RPIT 2021 vs 2024), E0759 lifetime of reference outlives lifetime of borrowed content, E0515 returns reference to local variable; fix patterns: explicit annotation, HRTB, 'static bound (when sound), restructure to remove borrow, `+ use<...>` opt-out for RPIT 2024. Keywords: E0106, E0623, E0495, E0700, E0759, E0515, "missing lifetime", "missing lifetime specifier", "lifetime mismatch", "cannot infer appropriate lifetime", "hidden type captures lifetime", "outlives", "doesn't live
Use when the user adds `#![no_std]`, supports embedded targets, needs the alloc crate, writes a `#[panic_handler]`, registers a `#[global_allocator]`, or designs a hybrid std + no_std library via feature flag. Prevents using std-only APIs in no_std, missing `#[panic_handler]`, picking alloc-free patterns when alloc is acceptable, and forgetting the `default = ["std"]` feature pattern. Covers: `#![no_std]` crate attribute, core crate (no allocation, no OS), alloc crate (Vec/Box/Rc/Arc/String when allocator available), `extern crate alloc;`, `#[panic_handler]` requirement when not std, `#[global_allocator]` hook, lang items (when needed in embedded), default = ["std"] feature pattern for hybrid library, testing no_std crates. Keywords: no_std, "#![no_std]", "no-std", embedded, core, alloc, "extern crate alloc", "panic_handler", "global_allocator", "lang items", "default = [std]", hybrid std, "no_std library", "no allocator", "embassy", "embedded Rust", "thumb target", "Cortex-M", "panic = abort", "core::fmt".
Use when the user binds a Rust library to C (cbindgen) or imports a C library into Rust (bindgen), declares `extern "C"` functions, uses `#[repr(C)]` types, manages opaque pointers, or works with file descriptors via `BorrowedFd` / `OwnedFd`. Prevents `unsafe extern` requirement misses in 2024, `Box<dyn Fn>` callback ABI issues, raw `c_char` ownership confusion, and fd-leak via raw `RawFd`. Covers: C FFI patterns (`extern "C"`, `#[repr(C)]`, `#[unsafe(no_mangle)]` in 2024, `unsafe extern` block in 2024), bindgen workflow (build.rs config, header inclusion, allowlist / blocklist), cbindgen workflow (cbindgen.toml, generate C header from Rust API), opaque types (pointer-to-incomplete pattern), string passing (CString / CStr / *const c_char), error handling across FFI, function-pointer callbacks, `BorrowedFd` / `OwnedFd` / `AsFd` / `AsRawFd` for unix fd safety, Drop guards for foreign resources. Keywords: FFI, "extern C", "#[repr(C)]", "#[no_mangle]", "#[unsafe(no_mangle)]", "unsafe extern", bindgen, cbindgen, "
Use when the user cross-compiles to another target triple, uses `rustup target add`, uses the `cross` crate, configures per-target linker via `.cargo/config.toml`, or guards code with `cfg(target_os = "...")`. Prevents missing target triple installation, picking wrong target for the use case (musl vs gnu, msvc vs gnu on Windows), and using `cfg` without `cfg_attr` for selective attributes. Covers: target triple format (arch-vendor-os-env), common triples (x86_64-unknown-linux-gnu, x86_64-unknown-linux-musl, aarch64-apple-darwin, x86_64-pc-windows-msvc, x86_64-pc-windows-gnu, wasm32-unknown-unknown, wasm32-wasi), `rustup target add`, `cargo build --target <triple>`, `cross` crate (container-based), conditional compilation `cfg(target_os = "...", target_arch = "...", target_pointer_width = "...", target_feature = "...")`, `cfg_attr`, `.cargo/config.toml` for per-target linker / runner. Keywords: "cross-compile", "cross compile", "target triple", "rustup target add", "cargo build --target", "cross crate", "musl
Use when the user writes a `build.rs`, generates code into `OUT_DIR`, links native libraries, triggers rebuilds via `cargo:rerun-if-changed`, sets `cargo:rustc-cfg`, or detects platform capabilities at build time. Prevents stale builds from missing `rerun-if-changed`, code generation in `src/`, native library link order mistakes, and missing `cargo:warning=` for non-fatal hints. Covers: build.rs basics (runs before package compile), `OUT_DIR` env var, directives (`cargo:rerun-if-changed=PATH`, `cargo:rerun-if-env-changed=VAR`, `cargo:rustc-cfg=KEY[=VALUE]`, `cargo:rustc-env=KEY=VALUE`, `cargo:rustc-link-lib`, `cargo:rustc-link-search`, `cargo:warning=`), generating code into `OUT_DIR` + `include!`, linking native libraries, bindgen workflow inside build.rs. Keywords: build.rs, "build script", "OUT_DIR", "cargo:rerun-if-changed", "cargo:rerun-if-env-changed", "cargo:rustc-cfg", "cargo:rustc-env", "cargo:rustc-link-lib", "cargo:rustc-link-search", "cargo:warning", "include!", "code generation", "build dependenc
Use when the user writes unit tests (`#[test]`), integration tests in `tests/`, doc tests, async tests, criterion benches, uses `cargo nextest`, or controls panicking tests via `#[should_panic]`. Prevents mixing integration tests in same crate, doc tests that compile only against stale signatures, async tests without runtime, and unguarded panicking tests. Covers: `#[test]` unit tests, `#[cfg(test)]` module convention, integration tests in `tests/` (each file is a separate crate), doc tests in /// comments, `cargo test --doc`, `#[should_panic]` / `#[should_panic(expected = "...")]`, `#[ignore]` for slow tests, `cargo nextest run`, property testing crates (proptest, quickcheck), snapshot testing (insta), criterion benches, common test helpers via `tests/common/mod.rs`. Keywords: test, "#[test]", "cargo test", "#[cfg(test)]", "tests directory", integration test, doc test, "cargo test --doc", "should_panic", ignore, "cargo test --ignored", "cargo nextest", nextest, criterion, benchmark, proptest, quickcheck, ins
Use when the user builds a CLI with clap 4.x, uses derive Parser API or builder API, defines subcommands, custom value parsers, env-var fallback, or shell completions. Prevents picking builder when derive suffices, missing `--features = ["derive"]`, omitting `value_parser` for non-string types, and confusing `Args` group with `Subcommand`. Covers: derive Parser API (`#[derive(Parser, Args, Subcommand, ValueEnum)]`), builder API (when derive is insufficient), nested Subcommand enums, `value_parser` (custom + range), env var fallback `env = "VAR"`, defaults `default_value` / `default_value_t`, required vs optional args, multiple values, shell completions via `clap_complete`, `Args` for shared argument groups. Keywords: clap, "#[derive(Parser)]", Parser, Subcommand, Args, ValueEnum, "clap derive", "clap builder", "value_parser", env, "default_value", "default_value_t", "shell completion", "clap_complete", "command line", CLI, argparse, "parse_from", "Parser::parse", subcommand, "nested command", required, "long
Use when the user derives Serialize / Deserialize, writes custom impls, picks enum representation (externally / internally / adjacently / untagged), uses `flatten` / `with` / `rename_all`, or chooses between JSON / TOML / YAML / bincode. Prevents enum-rep ambiguity, forgetting `serde(borrow)` for zero-copy `&'a str`, picking untagged with overlapping fields, and deriving without enabling the `derive` feature. Covers: Serialize / Deserialize derives, container attributes (rename_all, deny_unknown_fields, transparent, default, tag, content), field attributes (rename, skip, skip_serializing_if, default, with, serialize_with, deserialize_with, flatten, alias, borrow), enum representations, custom impl when derive insufficient, serde_json common patterns, format-crate selection (TOML / YAML / bincode / MessagePack). Keywords: serde, Serialize, Deserialize, "#[derive(Serialize, Deserialize)]", rename, rename_all, "#[serde(...)]", flatten, with, "serialize_with", "deserialize_with", skip, "skip_serializing_if", defa
Use when the user picks between Mutex / RwLock / atomics, designs Arc<Mutex<T>> patterns, deals with Mutex poisoning, uses scoped threads (1.63+), or needs Ordering enum for atomics. Prevents lock-ordering deadlocks, choosing Mutex when atomic suffices, ignoring poisoning, and Send/Sync mismatches. Covers: Arc<Mutex<T>> (thread-safe shared mutable state), Arc<RwLock<T>> (many readers OR one writer), atomics (AtomicBool / AtomicUsize / AtomicPtr / Ordering enum Relaxed/Acquire/Release/AcqRel/SeqCst), Mutex poisoning (.lock() returns Result), parking_lot (no poisoning, faster contention), lock ordering, scoped threads (std::thread::scope, 1.63+), thread_local!, compare-and-swap. Keywords: concurrency, "Arc<Mutex>", "Arc<RwLock>", Mutex, RwLock, atomic, AtomicBool, AtomicUsize, AtomicPtr, Ordering, Relaxed, Acquire, Release, AcqRel, SeqCst, "lock poisoning", "PoisonError", parking_lot, "lock ordering", "deadlock prevention", "scoped threads", "thread::scope", thread_local, "compare-and-swap", CAS, fetch_add, loc
Use when the user picks a channel: std::sync::mpsc (sync), tokio::sync::mpsc (async), tokio::sync::oneshot (single value), tokio::sync::broadcast (fan-out), tokio::sync::watch (latest-value), crossbeam-channel (lock-free + sync), or flume (alternative with select!). Prevents blocking the async executor by using std::sync::mpsc, picking unbounded when bounded is needed for backpressure, and using oneshot where mpsc fits. Covers: std::sync::mpsc (Sender / Receiver / sync_channel), tokio::sync::mpsc (bounded + unbounded), tokio::sync::oneshot (send + recv), tokio::sync::broadcast (fan-out, lagging consumer recovery), tokio::sync::watch (overwritable latest value), crossbeam-channel (lock-free, select! macro), flume (alternative). Backpressure patterns (bounded mpsc, try_send vs send().await). Keywords: channel, mpsc, oneshot, broadcast, watch, "std::sync::mpsc", "tokio::sync::mpsc", "tokio::sync::oneshot", "tokio::sync::broadcast", "tokio::sync::watch", crossbeam, flume, "bounded channel", "unbounded channel", b
Use when the user sets up a tokio runtime, spawns tasks, uses `select!`, applies timeouts, manages cancellation, uses `JoinSet` for structured concurrency, or chooses between current_thread and multi_thread runtime. Prevents blocking the executor with sync code, missing #[tokio::main], misusing block_on, and ignoring task-cancellation semantics. Covers: runtime setup via `#[tokio::main]` or `tokio::runtime::Runtime::new`, `tokio::spawn` vs `spawn_blocking` vs `task::block_in_place`, JoinHandle (abort, abort_handle, .await), `select!` macro (branches, biased mode, fallback), timeouts (`tokio::time::timeout`), cancellation via drop, `JoinSet` for structured concurrency (ordered + unordered joining), `tokio::task_local!`, blocking-in-async detection. Keywords: tokio, "#[tokio::main]", "tokio::spawn", spawn_blocking, "block_in_place", JoinHandle, "tokio::select!", select macro, timeout, "tokio::time::timeout", cancellation, "drop cancel", JoinSet, "structured concurrency", "task_local", current_thread, multi_thre
Use when the user designs Result-returning APIs, picks between Result and panic, uses the `?` operator with From conversion, defines custom error types, or considers core::error::Error (1.81) vs std::error::Error. Prevents `.unwrap()` in library code, hidden panics in `?` chains via wrong From impl, mixing thiserror and anyhow in library context, and forgetting source chain for error context. Covers: Result<T, E> vs Option<T>, `?` operator + From conversion chain, custom enum / struct error types, From impls for error conversion, the Error trait (std::error::Error, core::error::Error since 1.81 for no_std), source-chain pattern, panic vs Result decision, Result combinators (map / map_err / and_then / or_else / ok_or). Keywords: Result, Option, "? operator", From, "error conversion", "Error trait", "std::error::Error", "core::error::Error", "1.81 core error", "custom error", "error type", "thiserror vs anyhow", "library error", "panic vs Result", "map_err", "and_then", "or_else", "ok_or", "source chain", ".unw
Use when the user organises multiple crates into a Cargo workspace, sets up `[workspace.dependencies]` inheritance, manages member crates, chooses resolver 2 vs 3, or hits dependency drift across workspace members. Prevents dependency drift, repeated edition / rust-version specs across members, target-directory clutter, and accidental member-exclude. Covers: virtual workspace (top-level Cargo.toml with `[workspace]` only), workspace inheritance (`workspace = true`, `[workspace.dependencies]`, `[workspace.package]`, `[workspace.lints]`), member discovery (`members = []`, `default-members`, `exclude`), shared target directory, resolver versions 2 and 3 (when each matters), member-specific dependencies dev vs prod. Keywords: workspace, "Cargo workspace", "[workspace]", "virtual manifest", "workspace.dependencies", "workspace.package", "workspace.lints", "workspace = true", inheritance, "default-members", "exclude member", "shared target", "resolver = 2", "resolver = 3", "MSRV resolver", "multi-crate", monorepo,
Use when the user sets up a new Cargo crate, edits Cargo.toml, adds dependencies, configures features (additive principle), tunes profiles, uses `[patch]` / `[replace]`, declares lints in `[lints]`, or wants the MSRV-aware resolver behavior (1.84). Prevents non-additive feature design, mixing dev with build dependencies, accidental release-profile overrides, and missing `rust-version` declarations. Covers: `cargo new` vs `cargo init` (lib / bin), Cargo.toml structure ([package], [dependencies], [dev-dependencies], [build-dependencies], target-specific deps), version requirements (caret / tilde / exact / wildcards), features (additive principle, `dep:` prefix, weak `?` deps, default features), profiles (dev / release / test / bench / custom), `[patch]` and `[replace]`, `[lints]` table (recent stabilization), MSRV-aware resolver (1.84), `package` metadata fields. Keywords: cargo, "Cargo.toml", "cargo new", "cargo init", "cargo add", dependencies, features, "default features", "no-default-features", "dep:" prefi
Use when the user writes `unsafe fn` or `unsafe { }` blocks, dereferences raw pointers, calls FFI, uses `transmute`, deals with `MaybeUninit`, asks about undefined behavior, runs `miri`, or works with strict-provenance APIs (1.84). Prevents UB via aliasing violations, deref of a dangling pointer, breaking auto-trait invariants, missing `unsafe_op_in_unsafe_fn` warnings in edition 2024, and skipping `// SAFETY:` comments. Covers: the 8 superpowers post-2024 (deref raw ptr, call unsafe fn, access mut static, impl unsafe trait, union field, unsafe extern blocks, target_feature, unsafe attributes), undefined-behavior enumeration verbatim from the Reference, strict-provenance APIs (1.84: `expose_provenance`, `with_addr`, `map_addr`, `addr_of!`, `addr_of_mut!`), `unsafe_op_in_unsafe_fn` warn-by-default in 2024, soundness contracts, raw pointers vs references, `transmute`, `MaybeUninit`, `UnsafeCell`, miri verification. Keywords: unsafe, "unsafe fn", "unsafe block", "raw pointer", "*const", "*mut", "deref pointer",
Use when the user writes a derive macro / attribute macro / function-like proc-macro, parses TokenStream with `syn`, generates code with `quote!`, reports errors with `syn::Error`, or sets up a proc-macro crate. Prevents mixing proc-macro and library code in same crate, missing `proc-macro = true`, using compiler-side `proc_macro` directly outside the entry point, or producing unhygienic identifiers. Covers: three macro kinds (derive / attribute / function-like), `proc_macro` (compiler), `proc_macro2` (testable wrapper), `syn` (parsing), `quote!` (generation), span-aware errors via `syn::Error::new_spanned`, hygiene differences vs macro_rules, re-exporting macros from parent crate. Keywords: proc-macro, "procedural macro", "#[derive]", "derive macro", "attribute macro", "function-like macro", "proc_macro = true", proc_macro, proc_macro2, syn, "syn::Parse", quote, "quote!", TokenStream, "syn::Error", "compile_error!", span, hygiene, "diagnostic", "do_not_recommend", "do I need syn", "what is quote".
Use when the user writes a `macro_rules!`, debugs a macro hygiene issue, counts tokens via TT-munching, picks fragment specifiers, handles repetitions, or uses `$crate` for cross-crate macro references. Prevents fragment-specifier mismatches, identifier hygiene mistakes, missing `$crate` in exported macros, and naive recursion limits. Covers: `macro_rules!` declaration, all fragment specifiers (ident, expr, ty, pat, path, block, stmt, item, tt, meta, vis, literal, lifetime), repetition `$(...)+` `$(...)*` with separators, hygiene rules, `$crate`, TT-munching recursion, edition-2024 `expr` fragment widening, `macro_rules!` import scoping. Keywords: macro_rules, "declarative macro", "macro by example", fragment specifier, "ident expr ty pat path block stmt item tt meta vis literal lifetime", repetition, "$()*", "$()+", hygiene, "$crate", "TT munching", "recursion limit", "expr fragment 2024", "macro export", "macro_export", "macro_use", "what is $tt".
Use when the user writes `async fn`, awaits a future, uses AFIT (1.75) / RPITIT (1.75) / async closures (1.85), holds non-Send state across `.await`, needs the Pin / Unpin semantics, or hits Future-not-Send compile errors. Prevents holding MutexGuard or Rc across `.await`, calling `.poll` directly, confusing async fn with parallel execution, forgetting pinning when implementing Future manually, and edition-2024 RPIT precise-capturing surprises. Covers: `async fn` desugaring, `.await` suspension, async blocks, AFIT (1.75), RPITIT (1.75), async closures (1.85), Future contract (poll idempotency, waker invariant), Pin / Unpin (deep in references/pinning.md), cancellation via drop, holding non-Send across `.await`, edition 2024 RPIT lifetime capture interaction. Keywords: async fn, ".await", "async block", AFIT, RPITIT, "async trait", "async closure", "async ||", Future, "Future not Send", Pin, Unpin, "self-referential", "pinning projection", "structural pinning", "MutexGuard across await", "Send across await", "
Use when the user migrates a crate from edition 2021 to 2024, writes new edition-2024 code, hits the never-type fallback semantic change, encounters `unsafe extern` requirement, or wonders why RPIT lifetime capture default changed. Prevents writing pre-2024 idioms in 2024 code, missing the `cargo fix --edition` migration step, ignoring the `unsafe_op_in_unsafe_fn` lint becoming warn-by-default, or running into the `tail_expr_drop_order` change silently. Covers: all 13 edition-2024 changes shipped in Rust 1.85 (RPIT lifetime capture, never-type fallback, `unsafe extern`, `unsafe(no_mangle)` and `unsafe(link_section)`, `expr` fragment widening, prelude additions, `unsafe_op_in_unsafe_fn` warn-by-default, `if let` chains scope, `tail_expr_drop_order`, gen blocks status, `rust_2024_compatibility` lint group, reserved syntax), migration workflow. Keywords: edition 2024, "cargo fix --edition", "rust 2024", "1.85", "edition migration", "never type fallback", "! to ()", "unsafe extern", "unsafe(no_mangle)", "RPIT cap
Use when the user picks Box / Rc / Arc / RefCell / Cell / OnceCell / OnceLock / LazyLock / Weak / Pin, asks about reference counting, runtime-checked borrows, lazy globals, or breaking reference cycles. Prevents Arc<Mutex<T>> when atomic suffices, Rc across threads, holding a RefCell guard across calls, or static-mut lazy globals where OnceLock fits. Covers: Box (heap, recursive types, trait objects, leak), Rc (single-thread refcount, Weak), Arc (thread-safe refcount), RefCell (runtime borrow check), Cell (Copy interior), OnceCell, OnceLock (1.70), LazyLock (1.80), Weak<T> for cycle-breaking, Pin overview (deep ref in rust-syntax-async-await/references/pinning.md). Keywords: Box, Rc, Arc, RefCell, Cell, OnceCell, OnceLock, LazyLock, Weak, Pin, "smart pointer", "heap allocation", "reference counting", "lazy global", "cycle", "ref cycle", "interior mutability", "Rc<RefCell<T>>", "Arc<Mutex<T>>", "Arc<RwLock<T>>", "thread-safe", "Send Sync Rc", "what is Pin", "single thread", "multi thread".
Use when the user writes iterator chains (map / filter / fold / collect), implements `Iterator` manually, picks between `Fn` / `FnMut` / `FnOnce`, uses `move` closures, encounters closure capture-rules (edition 2021 disjoint captures), or writes async closures (1.85). Prevents using imperative loops where adapters fit, picking `FnOnce` when `Fn` would do, forgetting `move` for spawn-style closures, and confusing `collect` type inference. Covers: Iterator trait + Item type, adapters (map / filter / take / skip / fold / reduce / collect / sum / count / enumerate / zip / chain / flat_map), lazy evaluation, `collect::<Vec<_>>()` turbofish, custom Iterator impl, IntoIterator vs Iterator, `Fn` / `FnMut` / `FnOnce`, `move` closures, edition-2021 disjoint captures, async closures (1.85), returning closures (`Box<dyn Fn>` vs `impl Fn`). Keywords: Iterator, iter, "for loop", map, filter, fold, collect, "into_iter", "iter_mut", closure, "|x|", Fn, FnMut, FnOnce, "move closure", "async closure", "async ||", "disjoint cap
Use when the user defines or implements a trait, asks about default methods / supertraits / marker traits / blanket impls / sealed traits, encounters orphan-rule errors, or needs to choose between inherent impl and trait impl. Prevents orphan-rule violations, accidentally exposing an extensible trait users can implement, and confusing inherent vs trait methods. Covers: trait definition syntax (required + default methods), supertraits, marker traits (Send / Sync / Sized / Copy / Unpin), blanket impls, sealed trait pattern, inherent vs trait impl, orphan rule + coherence, derive macros (Copy / Clone / Debug / PartialEq / Eq / Hash / Default). Keywords: trait, "trait definition", "default method", supertrait, "marker trait", "blanket impl", "sealed trait", "orphan rule", coherence, "inherent impl", "impl Trait for Type", "newtype wrapper", "cannot impl foreign trait", derive, "#[derive]", "method not found", E0117, E0119, E0120, E0210, "what does trait do", "how to add method".
Use when the user needs `dyn Trait`, asks why a trait is not object-safe, chooses between `dyn Trait` and `impl Trait`, encounters upcasting (1.86), or uses precise capturing in trait definitions (1.87). Prevents picking `dyn Trait` when monomorphization is cheaper, missing object-safety rules, or using pre-1.86 upcasting work-arounds. Covers: `dyn Trait` type-erased dispatch, vtable representation, object-safety rules (no generic methods, no Sized self bound), `impl Trait` vs `dyn Trait` decision, trait upcasting `&dyn Sub` to `&dyn Super` (1.86), precise capturing `+ use<'a, T>` in trait definitions (1.87). Keywords: "dyn Trait", trait object, vtable, "object safety", "not object safe", E0038, "impl Trait", RPIT, "trait upcasting", "&dyn Sub", "as &dyn Super", "precise capturing", "+ use<>", "dyn dispatch", "static dispatch", "dynamic dispatch", "method resolution", "Box<dyn>", "Arc<dyn>", "&dyn", "monomorphization vs dyn", virtual.
Use when the user writes generic functions / types / impl blocks, needs trait bounds, where clauses, const generics, or wonders about monomorphization vs dyn dispatch trade-offs. Prevents over-constraining with `'static`, mixing up trait-bound syntax, or assuming generic Rust code emits runtime polymorphism (it doesn't, it's monomorphized). Covers: type parameters `<T>`, trait bounds `T: Trait`, multiple bounds with `+`, `where` clauses, monomorphization implications (code-size, compile-time), const generics (`N: usize`, where they can/cannot appear), generic lifetime parameters mixed with type parameters, default generic types (`<T = Default>`). Keywords: generic, "type parameter", "<T>", "trait bound", "where clause", "T: Trait", monomorphization, "code bloat", "const generic", "N: usize", "generic function", "generic struct", "generic impl", "default generic type", PhantomData generic, "compile time generics", "expanded at compile time", "generic over".
Use when the user writes code that triggers borrow-checker errors, asks "can I have & and &mut at the same time", encounters E0502 / E0499 / E0596, needs interior mutability (Cell / RefCell), splits a borrow across struct fields, or asks about reborrowing. Prevents borrow-checker fights via clone(), introduces interior mutability prematurely, or assumes NLL handles every case. Covers: `&T` (shared) vs `&mut T` (exclusive) rules, Non-Lexical Lifetimes (NLL), two-phase borrows, reborrowing, splitting borrows across struct fields and slices (`split_at_mut`), interior mutability (Cell for Copy, RefCell runtime-checked, Mutex thread-safe). Keywords: borrow, borrowing, "&", "&mut", "shared reference", "mutable reference", NLL, "non-lexical lifetimes", reborrow, "two-phase borrow", "split borrow", "split_at_mut", "interior mutability", Cell, RefCell, Mutex, E0502, E0499, E0596, "cannot borrow as mutable", "already borrowed", "multiple mutable borrows".
Use when the user writes Rust code that triggers ownership-transfer compile errors, asks "why moved value", asks to choose between Copy / Clone / Drop, encounters E0382 / E0507 / E0509 / E0382, or needs to design APIs around ownership transfer. Prevents excessive cloning, accidental moves, Copy+Drop mistakes, partial-move confusion, and ownership patterns that defeat the borrow checker. Covers: the three ownership rules, move semantics (by-value transfer on assignment / fn arg / return), Copy trait (which types qualify, why String / Vec / Box do not), Clone trait, scope-based drop and explicit `drop()`, ownership transfer patterns (builder, into-impl, by-value method receivers), partial moves out of fields. Keywords: ownership, move, moved value, "use of moved value", E0382, E0507, E0509, "cannot move out of", Copy, Clone, Drop, "drop function", scope, "ownership transfer", "by value", partial move, "move out of borrowed content", builder pattern, into method, "do I need to clone", "why can't I use this".
Use when the user must write a lifetime annotation, encounters E0106 / E0623 / E0495 / E0700 / E0759, needs to understand the three elision rules, the 'static bound vs &'static T, HRTB `for<'a>`, lifetime subtyping, variance (covariant / contravariant / invariant), or edition-2024 RPIT precise-capturing. Prevents over-annotating, confusing `T: 'static` (no internal short borrow) with `&'static T` (reference lives for program), or missing variance-related compile failures. Covers: explicit annotations, three elision rules, `'static` two senses, HRTB, lifetime subtyping (`'a: 'b`), variance, NLL behaviour reminder, edition-2024 RPIT capture (`+ use<'a, T>`). Keywords: lifetime, "'a", "lifetime annotation", "missing lifetime", "lifetime elision", "elision rule", "for<'a>", HRTB, "higher-rank trait bound", "'static", "static bound", variance, covariance, contravariance, invariance, PhantomData lifetime, E0106, E0623, E0495, E0700, E0759, "hidden lifetime", "precise capturing", "use<>", "doesn't live long enough",