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★ 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&Tor one&mut T. - Function signatures: take
&str/&[T]/&Tto borrow,Tto consume,&mut Tto 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/Arcfor shared ownership,RefCell/Mutex/RwLockfor interior mutability.- Self-referential structs do not work with plain references — use indices, arenas, or
Pin+ crates likeouroborosonly 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::Resultwith.context("...")for rich messages. ?propagates;unwrap()/expect()only for invariants (expectwith the reason) and in tests. Panics are for bugs, not for expected failures.
5. Concurrency
Send(can move to another thread) andSync(&Tcan be shared) are auto traits; the compiler rejects sharing non-thread-safe types (Rc,RefCell) across threads.- Patterns:
std::thread::scopefor borrowing data in threads,Arc<Mutex<T>>/Arc<RwLock<T>>, channels (std::sync::mpsc,crossbeam), data parallelism withrayon(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) — usetokio::time::sleep,spawn_blocking, or a rayon pool. tokio::spawnrequires'static + Sendfutures; useJoinSetto manage groups of tasks andCancellationToken(tokio-util) orselect!for shutdown.- Do not hold a
std::sync::Mutexguard across.await; usetokio::sync::Mutexonly when the lock must be held across awaits. async fnin traits is stable (1.75); use#[trait_variant::make(Send)]or explicitimpl Future + Sendwhen callers needSendfutures.
7. Unsafe
Keep unsafe blocks minimal, wrapped in safe APIs, each with a `
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
- 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), без исполняемых скриптов.
Похожие скиллы
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…