rust-coding-standards
БесплатноЗапускает вложенные скриптыНе проверенMaster Rust's ownership system, type safety, and zero-cost abstractions for building safe, concurrent, and performant systems. Covers borrowing, lifetimes…
Об этом скилле
Rust Coding Standards
Purpose: Master Rust's ownership system, type safety, and zero-cost abstractions for building safe, concurrent, and performant systems.
Level 1: Quick Reference
Core Principles
- Ownership: Each value has exactly one owner
- Borrowing: References allow multiple readers XOR one writer
- Zero-cost abstractions: High-level code compiles to optimal machine code
- Explicit over implicit: No hidden allocations or control flow
Ownership & Borrowing Cheat Sheet
// Ownership transfer (move)
let s1 = String::from("hello");
let s2 = s1; // s1 is now invalid
// Immutable borrow (multiple allowed)
let s = String::from("hello");
let r1 = &s;
let r2 = &s;
println!("{} and {}", r1, r2); // OK
// Mutable borrow (exclusive)
let mut s = String::from("hello");
let r1 = &mut s;
r1.push_str(" world");
// Copy types (stack-only)
let x = 5;
let y = x; // x is still valid (i32 implements Copy)
Result & Option
// Option: value may be absent
let name = find_user(42).map(|u| u.name).unwrap_or("Anonymous".into());
// Early return with ?
fn process() -> Result<(), Error> {
let config = parse_config("app.toml")?;
Ok(())
}
Essential Checklist
-
cargo clippy -- -D warnings -
cargo fmt -- --check -
cargo test -
cargo doc --no-deps -
cargo audit - Document all
unsafeblocks
Memory Safety Rules
- No data races: Compiler enforces at compile time
- No null pointers: Use
Option<T>instead - No dangling pointers: Borrow checker prevents
- No use-after-free: Ownership system prevents
- No buffer overflows: Bounds checking
Level 2: Implementation Guide
Ownership System
The Three Rules
- Each value has a variable that's its owner
- There can only be one owner at a time
- When the owner goes out of scope, the value is dropped
fn takes_ownership(s: String) {
println!("{}", s);
} // s dropped here
fn main() {
let s = String::from("hello");
takes_ownership(s); // s moved
// println!("{}", s); // Error: value borrowed after move
}
// Return ownership
fn gives_ownership() -> String {
String::from("hello")
}
Borrowing & References
// Multiple immutable borrows allowed
fn calculate_length(s: &String) -> usize {
s.len()
}
// Only one mutable borrow allowed
fn change(s: &mut String) {
s.push_str(", world");
}
// Non-lexical lifetimes
let mut s = String::from("hello");
let r1 = &s;
let r2 = &s;
println!("{} and {}", r1, r2); // last use of r1 and r2
let r3 = &mut s; // OK: r1 and r2 no longer used
Lifetime Annotations
// Specify reference relationships
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
// Struct with lifetime
struct Excerpt<'a> {
part: &'a str,
}
// Lifetime elision: compiler infers in common patterns
fn first_word(s: &str) -> &str { /* elided lifetimes */ }
Traits & Generics
pub trait Summary {
fn summarize(&self) -> String;
// Default implementation
fn full_summary(&self) -> String {
format!("Read more: {}", self.summarize())
}
}
impl Summary for Article {
fn summarize(&self) -> String {
format!("{} by {}", self.headline, self.author)
}
}
// Trait bounds
pub fn notify<T: Summary + Display>(item: &T) {
println!("Breaking: {}", item.summarize());
}
// where clause for readability
pub fn process<T, U>(t: &T, u: &U) -> String
where
T: Display + Clone,
U: Clone + Debug,
{
format!("{:?}", u)
}
Common Derived Traits
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct User {
pub id: u32,
pub name: String,
}
Error Handling
use thiserror::Error;
#[derive(Error, Debug)]
pub enum AppError {
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
#[error("Database error: {0}")]
Database(#[from] sqlx::Error),
#[error("Not found: {0}")]
NotFound(String),
}
pub type Result<T> = std::result::Result<T, AppError>;
// With anyhow for context
use anyhow::Context;
fn read_config() -> anyhow::Result<Config> {
let content = fs::read_to_string("config.toml")
.context("Failed to read config file")?;
Ok(toml::from_str(&content)?)
}
Async/Await
use tokio;
#[tokio::main]
async fn main() -> Result<()> {
let result = fetch_data().await?;
process(result).await?;
Ok(())
}
// Concurrent execution
let futures = urls.iter().map(|url| fetch_url(url));
let results = futures::future::join_all(futures).await;
// Spawn tasks
let handle = tokio::spawn(async move {
expensive_computation().await
});
let result = handle.await?;
Channels
use tokio::sync::mpsc;
let (tx, mut rx) = mpsc::channel(32);
// Producer
tokio::spawn(async move {
tx.send(work).await.unwrap();
});
// Consumer
while let Some(result) = rx.recv().await {
Установить rust-coding-standards в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл rust-coding-standards?
Master Rust's ownership system, type safety, and zero-cost abstractions for building safe, concurrent, and performant systems. Covers borrowing, lifetimes, traits, error handling, async/await, and testing patterns.
Как установить скилл rust-coding-standards?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл rust-coding-standards запускает скрипты?
Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.
Похожие скиллы
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