Command Palette

Search for a command to run...

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

rust-advanced

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

Advanced Rust on Windows, macOS, and Linux: ownership and lifetimes, Result/error design, async Tokio, concurrency, serde/clap/tracing, Cargo features and…

deepseekoracleот deepseekoracle332 установки в других каталогах

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

Rust Advanced

Audited toolchain: rustc 1.93.1, cargo 1.93.1, rustup installed. A cargo new + cargo run smoke test returned Hello, world! (exit 0).

1. Mental model

Rust's compiler is a design partner, not an obstacle. Most fights come from one of these:

  • Ownership: one owner; moving invalidates the old binding.
  • Borrowing: many immutable borrows OR one mutable borrow, not both.
  • Lifetimes: a reference cannot outlive its data.
  • Send/Sync: a value crossing threads/await points must be safe to move/share.
  • Errors are values: Result<T, E> is normal control flow.

When stuck, ask:

  1. Who owns this value?
  2. How long must it live?
  3. Does it cross a thread or an await point?
  4. Can I return an owned value instead of a reference?
  5. Can I narrow the borrow scope?

2. Toolchain and project

rustup show
rustup update stable
rustup component add rustfmt clippy rust-src
rustup target list --installed
cargo --version

New project:

cargo new app --bin
cargo new libname --lib
cargo add serde --features derive
cargo add tokio --features full
cargo add anyhow thiserror

Workspace:

[workspace]
members = ["app", "core", "cli"]
resolver = "2"

Cargo.toml baseline:

[package]
name = "app"
version = "0.1.0"
edition = "2024"
rust-version = "1.85"

[dependencies]
anyhow = "1"
thiserror = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
clap = { version = "4", features = ["derive"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }

[profile.release]
opt-level = 3
lto = "thin"
codegen-units = 1
strip = "symbols"
panic = "abort"

Use edition = "2024" only if the toolchain supports it; otherwise pin 2021.

3. Ownership, borrowing, lifetimes

fn takes_owned(s: String) { println!("{s}"); }

fn borrows(s: &str) -> usize { s.len() }

fn main() {
    let s = String::from("hello");
    let n = borrows(&s);       // borrow ends here
    takes_owned(s);            // move is now allowed
    println!("{n}");
}

Rules that fix most errors:

  • Return String/Vec<T> when the caller must own the data.
  • Accept &str/&[T] when you only read.
  • Keep mutable borrows short; do not hold one across a call that also borrows.
  • Use clone() deliberately at boundaries, not to silence every error.
  • Cow<'a, str> for optionally borrowed strings.
  • Arc<T> for shared ownership across threads; Rc<T> is single-thread only.
  • RefCell<T> for interior mutability in single-thread code; Mutex/RwLock across threads.

Lifetime template:

struct Parser<'a> {
    input: &'a str,
}

impl<'a> Parser<'a> {
    fn new(input: &'a str) -> Self { Self { input } }
    fn rest(&self) -> &'a str { self.input }
}

If a lifetime is hard, first try owning the data; optimize to borrow later.

4. Errors

Use Result for recoverable errors; panic! only for bugs/invariants.

use thiserror::Error;

#[derive(Debug, Error)]
pub enum AppError {
    #[error("io: {0}")]
    Io(#[from] std::io::Error),
    #[error("bad config: {0}")]
    Config(String),
}

pub fn load(path: &str) -> Result<String, AppError> {
    let s = std::fs::read_to_string(path)?;
    if s.is_empty() { return Err(AppError::Config("empty".into())); }
    Ok(s)
}
  • Libraries: custom thiserror enum, no anyhow in public API.
  • Applications: anyhow::Result<T> at the top; add context with .context("...")?.
  • Never .unwrap() on user input, files, network, or env vars.
  • ? converts via From; implement From or use #[from].
  • Preserve the source chain; do not stringify and discard it.

5. Async and concurrency

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let a = tokio::spawn(async { 1 + 1 });
    let b = tokio::spawn(async { 2 + 2 });
    println!("{} {}", a.await?, b.await?);
    Ok(())
}

Rules:

  • Use Tokio for I/O concurrency; do not use it for CPU-bound work without spawn_blocking.
  • Never block the async executor with std::thread::sleep, synchronous file I/O, or a long CPU loop.
  • tokio::time::timeout around network calls.
  • tokio::select! for cancellation/racing.
  • Arc<Mutex<T>> or channels for shared state; prefer message passing.
  • Mutex guard cannot be held across .await unless using tokio::sync::Mutex.
  • Send errors usually mean an Rc, RefCell, or non-Send guard is held across await.

Threads:

use std::sync::{Arc, Mutex};
let state = Arc::new(Mutex::new(0));
let s2 = Arc::clone(&state);
std::thread::spawn(move || *s2.lock().unwrap() += 1);

Use crossbeam-channel or std::sync::mpsc; for async use tokio::sync::mpsc.

6. Serde, clap, tracing

use clap::Parser;
use serde::{Deserialize, Serialize};

#[derive(D
Полный SKILL.md на ClawHub

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

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

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

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

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

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

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

FAQ

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

Advanced Rust on Windows, macOS, and Linux: ownership and lifetimes, Result/error design, async Tokio, concurrency, serde/clap/tracing, Cargo features and profiles, testing, profiling, cross-compilation, Windows FFI, and PyO3/maturin. Use when the borrow checker, an async Send error, a linker error, a version conflict, or a production binary needs a real diagnosis.

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

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

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

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

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

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