toolchains-rust-core
БесплатноБез исполняемых скриптовНе проверенRust 2024 edition core patterns: idiomatic code, error handling, traits/generics, macros, async/concurrency, testing, and project architecture
от bobmatnyc★ 160 звёзд на GitHubОб этом скилле
Rust 2024 Core Patterns
Quick Start
# Cargo.toml - essential stack
[dependencies]
tokio = { version = "1", features = ["full"] }
thiserror = "2"
anyhow = "2"
serde = { version = "1", features = ["derive"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
[dev-dependencies]
rstest = "0.22"
proptest = "1"
mockall = "0.13"
insta = "1"
criterion = { version = "0.5", features = ["html_reports"] }
cargo add tokio --features full && cargo add thiserror anyhow serde --features serde/derive
cargo clippy -- -D warnings # enforce in CI
cargo test # unit + integration + doctests
cargo test --doc # doctests only
Idiomatic Patterns
- Builder pattern: Use consuming
selfmethods; finish withbuild() -> Result<T, E>for validated construction. - Newtype pattern:
struct UserId(u64)gives type safety at zero cost; addimpl From<u64> for UserId. - From/Into: Implement
From<T>only —Into<T>is blanket-provided; acceptimpl Into<T>in function params. - Derive by default:
#[derive(Debug, Clone, PartialEq, Eq, Hash)]on domain types; addserdeonly when needed. - Type state: Encode state machines as generic marker types — invalid transitions become compile errors, not panics.
- Borrowed params: Accept
&strnot&String,&[T]not&Vec<T>,impl AsRef<Path>not&PathBuf. - Default for config:
Config { field: value, ..Default::default() }— audit all fields when adding new ones. - RAII guards: Use
Dropfor resource cleanup; wrap locks, file handles, and connections in guard types. Cow<'_, str>: ReturnCow<'_, str>when sometimes borrowing, sometimes owning — avoids unnecessary clones.- Zero-cost abstractions: Iterator chains compile to identical (often better) machine code than manual loops.
- Stack vs heap: Default to stack; use
Boxonly for trait objects, recursive types, or large data escaping scope.
Error Handling
thiserror (libraries)
use thiserror::Error;
#[derive(Error, Debug)]
pub enum UserError {
#[error("user {id} not found")]
NotFound { id: u64 },
#[error("invalid email: {0}")]
InvalidEmail(String),
#[error("database error")]
Database(#[from] sqlx::Error),
#[error("serialization failed")]
Serialization(#[from] serde_json::Error),
}
Rules:
- Libraries expose typed error enums — callers can pattern-match variants.
- Never use
StringorBox<dyn Error>in public library API. #[from]generatesFrom<SourceError>— use?to propagate automatically.#[source]exposes the underlying error viaError::source()without auto-From.
anyhow (applications / CLIs)
use anyhow::{Context, Result};
fn load_config(path: &Path) -> Result<Config> {
let text = std::fs::read_to_string(path)
.with_context(|| format!("reading config from {}", path.display()))?;
let config: Config = toml::from_str(&text)
.context("parsing config as TOML")?;
Ok(config)
}
fn main() -> Result<()> {
let config = load_config(Path::new("config.toml"))?;
run(config)
}
Rules:
anyhow::Result<T>inmain(), CLI handlers, and top-level application code.- Chain context with
.context("what we were doing")at each call site. - Never use
anyhowin public library APIs — wrap and convert at the boundary.
Error conversion at library/app boundary
// In application code: convert library error to anyhow
let user = user_service.get(id)
.await
.map_err(|e| anyhow::anyhow!("get user {id}: {e}"))?;
// Or implement From in your app error type
impl From<UserError> for AppError { ... }
Traits and Generics
Small, focused traits
// Prefer small traits over large catch-all interfaces
trait Fetch {
async fn fetch(&self, url: &str) -> Result<Bytes, FetchError>;
}
trait Store {
async fn store(&self, key: &str, value: &[u8]) -> Result<(), StoreError>;
}
// Compose with supertraits
trait Cache: Fetch + Store + Send + Sync {}
Trait objects vs generics
// Generics: compile-time dispatch, monomorphized, no heap alloc
fn process<F: Fetch>(fetcher: &F) -> Result<()> { ... }
// Trait objects: runtime dispatch, heap alloc, heterogeneous collections
fn process_dyn(fetcher: &dyn Fetch) -> Result<()> { ... }
fn process_arc(fetcher: Arc<dyn Fetch>) -> Result<()> { ... }
// Rule: default to generics; use dyn Trait for:
// - Heterogeneous collections (Vec<Box<dyn Trait>>)
// - Runtime polymorphism (DI containers, plugin systems)
// - Avoiding monomorphization bloat in large codebases
Associated types vs generics
// Associated type: one implementation per type (Iterator pattern)
trait Parser {
type Output;
fn parse(&self, input: &str) -> Result<Self::Output, ParseError>;
}
// Generic parameter: multiple implementations per type
trait Convert<T> {
fn convert(&self)
Установить toolchains-rust-core в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл toolchains-rust-core?
Rust 2024 edition core patterns: idiomatic code, error handling, traits/generics, macros, async/concurrency, testing, and project architecture
Как установить скилл toolchains-rust-core?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл toolchains-rust-core запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic