Command Palette

Search for a command to run...

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

rust

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

Rust programming patterns and ownership concepts

miles990от miles990★ 26 звёзд на GitHub5 установок в других каталогах

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

Rust

Overview

Rust programming patterns including ownership, lifetimes, traits, and async programming.


Ownership and Borrowing

Basic Ownership

fn main() {
    // Ownership transfer (move)
    let s1 = String::from("hello");
    let s2 = s1; // s1 is moved to s2
    // println!("{}", s1); // Error: s1 is no longer valid

    // Clone for deep copy
    let s3 = String::from("hello");
    let s4 = s3.clone();
    println!("{} {}", s3, s4); // Both valid

    // Copy types (stack-only data)
    let x = 5;
    let y = x; // Copy, not move
    println!("{} {}", x, y); // Both valid
}

// Ownership and functions
fn takes_ownership(s: String) {
    println!("{}", s);
} // s is dropped here

fn makes_copy(x: i32) {
    println!("{}", x);
} // x goes out of scope, nothing special

fn gives_ownership() -> String {
    String::from("hello")
}

fn takes_and_gives_back(s: String) -> String {
    s
}

Borrowing

// Immutable borrow
fn calculate_length(s: &String) -> usize {
    s.len()
} // s goes out of scope but doesn't drop the value

// Mutable borrow
fn append_world(s: &mut String) {
    s.push_str(" world");
}

fn main() {
    let s = String::from("hello");

    // Multiple immutable borrows OK
    let r1 = &s;
    let r2 = &s;
    println!("{} {}", r1, r2);

    // Mutable borrow (only one at a time)
    let mut s2 = String::from("hello");
    let r3 = &mut s2;
    r3.push_str(" world");
    println!("{}", r3);

    // Cannot have mutable and immutable at same time
    let mut s3 = String::from("hello");
    let r4 = &s3;
    // let r5 = &mut s3; // Error!
    println!("{}", r4);
}

Lifetimes

// Explicit lifetime annotations
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,
}

impl<'a> Excerpt<'a> {
    fn level(&self) -> i32 {
        3
    }

    fn announce_and_return(&self, announcement: &str) -> &str {
        println!("Attention: {}", announcement);
        self.part
    }
}

// Multiple lifetimes
fn complex<'a, 'b>(x: &'a str, y: &'b str) -> &'a str
where
    'b: 'a, // 'b outlives 'a
{
    x
}

// Static lifetime
fn static_string() -> &'static str {
    "I live forever"
}

Structs and Enums

Structs

#[derive(Debug, Clone, PartialEq)]
struct User {
    id: u64,
    email: String,
    name: String,
    active: bool,
}

impl User {
    // Associated function (constructor)
    fn new(email: String, name: String) -> Self {
        Self {
            id: generate_id(),
            email,
            name,
            active: true,
        }
    }

    // Method
    fn deactivate(&mut self) {
        self.active = false;
    }

    // Method returning reference
    fn email(&self) -> &str {
        &self.email
    }
}

// Tuple struct
struct Color(u8, u8, u8);
struct Point(f64, f64, f64);

// Unit struct
struct AlwaysEqual;

Enums

// Basic enum
enum Direction {
    North,
    South,
    East,
    West,
}

// Enum with data
enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(u8, u8, u8),
}

impl Message {
    fn process(&self) {
        match self {
            Message::Quit => println!("Quit"),
            Message::Move { x, y } => println!("Move to ({}, {})", x, y),
            Message::Write(text) => println!("Write: {}", text),
            Message::ChangeColor(r, g, b) => println!("Color: ({}, {}, {})", r, g, b),
        }
    }
}

// Result and Option
fn divide(a: f64, b: f64) -> Result<f64, String> {
    if b == 0.0 {
        Err(String::from("Division by zero"))
    } else {
        Ok(a / b)
    }
}

fn find_user(id: u64) -> Option<User> {
    // ...
    None
}

Traits

// Trait definition
trait Summary {
    fn summarize(&self) -> String;

    // Default implementation
    fn summarize_author(&self) -> String {
        String::from("(unknown author)")
    }
}

// Implement trait
impl Summary for User {
    fn summarize(&self) -> String {
        format!("{} ({})", self.name, self.email)
    }
}

// Trait bounds
fn notify<T: Summary>(item: &T) {
    println!("Breaking news: {}", item.summarize());
}

// Multiple trait bounds
fn notify_multiple<T: Summary + Clone>(item: &T) {
    let cloned = item.clone();
    println!("{}", cloned.summarize());
}

// where clause
fn some_function<T, U>(t: &T, u: &U) -> i32
where
    T: Summary + Clone,
    U: Clone + std::fmt::Debug,
{
    // ...
    0
}

// Return trait
fn create_summarizable() -> impl Summary {
    User::new(
        String::from("[email protected]"),
        String::from("Test"),
    )
}

// Trait objects (dynamic dispatch)
fn process_summaries(items: &[&dyn Summary]) {
    for item in items {
        println!("{}", item.summarize());
    }
}

Error Handling

use std::fs::File;
use std::io::{self, Read};
use thiserror::Error;

// Custom error with thiserror
#[derive(E
Полный SKILL.md на GitHub

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

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

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

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

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

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

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

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

templates/Cargo.tomltemplates/README.md

FAQ

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

Rust programming patterns and ownership concepts

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

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

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

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

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

Сравнить rust с