Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

toolchains-rust-core

БесплатноБез исполняемых скриптовНе проверен

Rust 2024 edition core patterns: idiomatic code, error handling, traits/generics, macros, async/concurrency, testing, and project architecture

bobmatnycот 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 self methods; finish with build() -> Result<T, E> for validated construction.
  • Newtype pattern: struct UserId(u64) gives type safety at zero cost; add impl From<u64> for UserId.
  • From/Into: Implement From<T> only — Into<T> is blanket-provided; accept impl Into<T> in function params.
  • Derive by default: #[derive(Debug, Clone, PartialEq, Eq, Hash)] on domain types; add serde only when needed.
  • Type state: Encode state machines as generic marker types — invalid transitions become compile errors, not panics.
  • Borrowed params: Accept &str not &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 Drop for resource cleanup; wrap locks, file handles, and connections in guard types.
  • Cow<'_, str>: Return Cow<'_, 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 Box only 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 String or Box<dyn Error> in public library API.
  • #[from] generates From<SourceError> — use ? to propagate automatically.
  • #[source] exposes the underlying error via Error::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> in main(), CLI handlers, and top-level application code.
  • Chain context with .context("what we were doing") at each call site.
  • Never use anyhow in 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)
Полный SKILL.md на GitHub

Установить 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), без исполняемых скриптов.

Похожие скиллы

Сравнить toolchains-rust-core с