rust-expert
Rust programming expert including ownership, borrowing, lifetimes, async Tokio patterns, error handling, trait system, performance optimization, testing, and…
от oimiragieo★ 48 звёзд на GitHub
Установить rust-expert в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
Rust Expert
Apply idiomatic Rust patterns with strong safety, performance, and maintainability guarantees.
Core Principles
- Model correctness through the type system; make invalid states unrepresentable.
- Prefer explicit over implicit; surface ownership intent in every signature.
- Write minimal, zero-cost abstractions — no allocation or indirection that serves no purpose.
- Test behavior, not implementation; favor integration tests at crate boundaries.
1. Ownership, Borrowing, and Lifetimes
Ownership Patterns
// Prefer moves when value is consumed; prefer borrows when value is shared.
fn process(data: Vec<u8>) -> Vec<u8> { /* consumes */ }
fn inspect(data: &[u8]) -> usize { data.len() /* borrows */ }
// Clone only when necessary and explicitly documented.
// Anti-pattern: clone() to silence borrow checker errors — fix the design instead.
Borrowing Rules (enforce at design time)
- Only one mutable reference OR any number of immutable references at a time.
- References must not outlive the value they point to.
- Use
Cow<'a, T>when you need borrow-or-own semantics without forcing allocation.
use std::borrow::Cow;
fn normalize(s: &str) -> Cow<str> {
if s.contains(' ') {
Cow::Owned(s.replace(' ', "_"))
} else {
Cow::Borrowed(s)
}
}
Lifetime Patterns
// Explicit lifetime annotation: only when compiler cannot infer.
struct Parser<'input> {
source: &'input str,
pos: usize,
}
impl<'input> Parser<'input> {
fn next_token(&mut self) -> &'input str {
// Returns a slice of the original input — lifetime ties result to source.
&self.source[self.pos..]
}
}
// RPIT (Return Position Impl Trait) avoids lifetime noise in many cases.
fn words(s: &str) -> impl Iterator<Item = &str> {
s.split_whitespace()
}
Anti-Patterns to Avoid
clone()inside hot loops to avoid borrow checker.unsafeto bypass lifetime checks — redesign instead.'staticbounds that force heap allocation when borrowing suffices.- Storing
&mut Tin structs — prefer owned data orRefCell<T>.
2. Error Handling
Decision Matrix
| Scenario | Tool |
|---|---|
| Library crate errors | thiserror — typed, composable |
| Application / binary errors | anyhow — ergonomic ? chaining |
| Domain-specific context | Custom enum via thiserror |
| Infallible conversions | From / Into — zero overhead |
thiserror (Library Crates)
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ConfigError {
#[error("missing required field: {field}")]
MissingField { field: &'static str },
#[error("invalid value for {field}: {source}")]
ParseError { field: &'static str, #[source] source: std::num::ParseIntError },
#[error(transparent)]
Io(#[from] std::io::Error),
}
anyhow (Application / Binary)
use anyhow::{Context, Result};
fn load_config(path: &str) -> Result<Config> {
let raw = std::fs::read_to_string(path)
.with_context(|| format!("reading config from {path}"))?;
toml::from_str(&raw).context("parsing config TOML")
}
Error Propagation Rules
- Never use
.unwrap()in library code; use.expect()only in tests andmain()where the invariant is self-evident. - Add
.context()/.with_context()at every error boundary to preserve the call chain. - Map errors at crate boundaries — do not leak internal error types in public APIs.
3. Trait System
Generics vs Trait Objects
// Prefer generics (monomorphized, zero-cost) when types are known at compile time.
fn serialize<S: Serialize>(value: &S) -> Vec<u8> { /* ... */ }
// Use dyn Trait only when you need heterogeneous collections or runtime dispatch.
fn handlers() -> Vec<Box<dyn EventHandler>> { /* ... */ }
Where Clauses
// Prefer where clauses for readability when bounds are complex.
fn merge<K, V>(a: HashMap<K, V>, b: HashMap<K, V>) -> HashMap<K, V>
where
K: Eq + Hash,
V: Clone,
{ /* ... */ }
Blanket Implementations and Orphan Rules
- Implement standard traits (
Display,From,Iterator) for your types. - Respect the orphan rule: you may only implement a foreign trait for a local type.
- Use the newtype pattern to work around orphan restrictions.
struct Wrapper(Vec<u8>);
impl fmt::Display for Wrapper {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.0)
}
}
Rust 1.75+ Async in Traits (RPITIT)
// Stable as of Rust 1.75 — no more async-trait macro needed.
trait DataSource {
async fn fetch(&self, id: u64) -> anyhow::Result<Record>;
}
// Return-Position Impl Trait in Traits (RPITIT) — also stable in 1.75.
trait Transformer {
fn transform(&self, input: &str) -> impl Iterator<Item = String>;
}
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
- 01
Read - 02
Write - 03
Edit - 04
Bash - 05
Grep - 06
Glob
Вложенные файлы
- commands/rust-expert.md
- hooks/post-execute.cjs
- hooks/pre-execute.cjs
- references/research-requirements.md
- rules/rust-expert.md
- schemas/input.schema.json
- schemas/output.schema.json
- scripts/main.cjs
- templates/implementation-template.md
FAQ
Что делает скилл rust-expert?
Rust programming expert including ownership, borrowing, lifetimes, async Tokio patterns, error handling, trait system, performance optimization, testing, and production systems development
Как установить скилл rust-expert?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл rust-expert запускает скрипты?
Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.
Похожие скиллы
theme-factory
AnthropicToolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
access
AnthropicManage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
configure
AnthropicSet up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
access
AnthropicManage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…