Command Palette

Search for a command to run...

Назад к скиллам
скилл № 23334

lang-rust

Use when the user asks about Rust, cargo, the borrow checker, lifetimes, ownership, traits and generics, Result and ?, thiserror/anyhow, Tokio async Rust…

БесплатноБез исполняемых скриптов
j4flmaoот j4flmao★ 47 звёзд на GitHub

Установить lang-rust в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Об этом скилле

Rust

Purpose

Rust guarantees memory safety and freedom from data races in safe code through ownership and borrowing, with performance comparable to C/C++. Productivity comes from designing data so the borrow checker agrees, using the type system for errors and states, and keeping unsafe small and audited. This skill covers those idioms for current stable Rust (2024 edition).

Agent Protocol

Trigger

"Rust", "cargo", "borrow checker", "lifetimes", "ownership", "traits", "Result", "thiserror", "anyhow", "tokio", "async Rust", "Send/Sync", "unsafe", "clippy".

Input Context

  • Rust toolchain/MSRV and edition; crate type (binary, library, workspace)
  • Runtime (sync, Tokio, embedded) and key dependencies
  • The compiler error or code to review

Output Artifact

Rust code, Cargo.toml changes, or an explanation of a borrow-checker error with the fix. No file unless requested.

Response Format

Toolchain: {1.xx, edition 2024}
Problem/Goal: {what}
Code: {snippet}
Why it compiles/is sound: {ownership/lifetime reasoning}
Verify: cargo clippy -- -D warnings && cargo test

1. Ownership and Borrowing

  • Each value has one owner; assignment/pass-by-value moves it (unless Copy). At any time: many &T or one &mut T.
  • Function signatures: take &str/&[T]/&T to borrow, T to consume, &mut T to modify; return owned values.
  • Fixing borrow errors: shorten borrows (scope blocks, compute indices first), split structs so fields are borrowed independently, use indices/IDs instead of references between objects, or move ownership.
  • .clone() is fine for small or reference-counted data; in hot paths prefer borrowing. Rc/Arc for shared ownership, RefCell/Mutex/RwLock for interior mutability.
  • Self-referential structs do not work with plain references — use indices, arenas, or Pin + crates like ouroboros only when unavoidable.

2. Lifetimes

Lifetimes name how long borrows are valid; elision rules cover most functions. Annotate when returning a reference derived from inputs:

fn longest<'a>(a: &'a str, b: &'a str) -> &'a str { if a.len() >= b.len() { a } else { b } }

Structs holding references need lifetime parameters (struct Parser<'src> { input: &'src str }); if that spreads everywhere, store owned data instead.

3. Traits and Generics

  • Generics (fn f<T: Display>(x: T) / impl Display) are monomorphised: zero-cost dispatch, larger binaries. Trait objects (Box<dyn Trait>, &dyn Trait) use a vtable: one copy of code, dynamic dispatch.
  • Implement standard traits so types compose: Debug, Clone, PartialEq/Eq/Hash, Default, From/TryFrom, Display, Iterator.
  • Encode states in types (typestate) to make invalid sequences unrepresentable — see references/typestate-pattern-generics.md.

4. Error Handling

use thiserror::Error;

#[derive(Debug, Error)]
pub enum ConfigError {
    #[error("reading {path}: {source}")]
    Io { path: String, #[source] source: std::io::Error },
    #[error("invalid port {0}")]
    InvalidPort(u32),
}

pub fn load(path: &str) -> Result<Config, ConfigError> {
    let text = std::fs::read_to_string(path)
        .map_err(|source| ConfigError::Io { path: path.to_owned(), source })?;
    parse(&text)
}
  • Libraries: typed errors with thiserror. Applications: anyhow::Result with .context("...") for rich messages.
  • ? propagates; unwrap()/expect() only for invariants (expect with the reason) and in tests. Panics are for bugs, not for expected failures.

5. Concurrency

  • Send (can move to another thread) and Sync (&T can be shared) are auto traits; the compiler rejects sharing non-thread-safe types (Rc, RefCell) across threads.
  • Patterns: std::thread::scope for borrowing data in threads, Arc<Mutex<T>>/Arc<RwLock<T>>, channels (std::sync::mpsc, crossbeam), data parallelism with rayon (par_iter()).

6. Async with Tokio

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let client = reqwest::Client::builder().timeout(std::time::Duration::from_secs(5)).build()?;
    let (a, b) = tokio::try_join!(
        client.get("https://example.com/a").send(),
        client.get("https://example.com/b").send(),
    )?;
    println!("{} {}", a.status(), b.status());
    Ok(())
}
  • Futures are lazy and cooperative: never block inside async code (std::thread::sleep, heavy CPU, blocking I/O) — use tokio::time::sleep, spawn_blocking, or a rayon pool.
  • tokio::spawn requires 'static + Send futures; use JoinSet to manage groups of tasks and CancellationToken (tokio-util) or select! for shutdown.
  • Do not hold a std::sync::Mutex guard across .await; use tokio::sync::Mutex only when the lock must be held across awaits.
  • async fn in traits is stable (1.75); use #[trait_variant::make(Send)] or explicit impl Future + Send when callers need Send futures.

7. Unsafe

Keep unsafe blocks minimal, wrapped in safe APIs, each with a `

Полный SKILL.md на GitHub

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

  • references/rust-advanced.md
  • references/rust-fundamentals.md
  • references/rust-testing.md
  • references/typestate-pattern-generics.md

FAQ

Что делает скилл lang-rust?

Use when the user asks about Rust, cargo, the borrow checker, lifetimes, ownership, traits and generics, Result and ?, thiserror/anyhow, Tokio async Rust, Send/Sync, unsafe Rust, clippy or the Rust 2024 edition. Produces idiomatic Rust with tests. Not for Rust web architecture (use rust-architecture) or no_std firmware (use bare-metal-rust).

Как установить скилл lang-rust?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл lang-rust запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

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

Сравнить lang-rust с