Przejdź do treści
Biblioteka skilli
Programowanie · Budowanie i kod

rust-best-practices

/rust-best-practices

Stosuje wytyczne Microsoft Pragmatic Rust przy każdej edycji kodu Rust: obsługa błędów, projekt API, wydajność i idiomy.

Repozytorium
spellbook ↗
Licencja
MIT
Ostatnia zmiana repozytorium
26.10.2026

Ocena i bezpieczeństwo

100/ 100Klasa: dobry
Format25 / 25
Frontmatter z nazwą i opisem, poprawna nazwa, opis do 1024 znaków, nazwa zgodna z folderem.
Odkrywalność25 / 25
Opis mówi, kiedy użyć skilla, ma sensowną długość i jest w 3. osobie.
Treść35 / 35
Co najmniej 150 słów i do 500 linii, nagłówki, listy kroków, przykłady albo kod.
Higiena15 / 15
Bez zaślepek typu TODO, bez ścieżek Windows, z licencją.
Ryzykobrak sygnałów w skanie
Pliki w paczce
2
Skrypty
0
Komentarze HTML
0
Adresy URL w SKILL.md
3
Przestarzałość

Brak sygnałów. Repozytorium zmienione 26.10.2026, bez odwołań do wycofanych modeli i API.

Licencja

MIT, otwarta: można używać i zmieniać, z zachowaniem informacji o autorze.

Co robi i kiedy

Stosuje wytyczne Microsoft Pragmatic Rust przy każdej edycji kodu Rust: obsługa błędów, projekt API, wydajność i idiomy.

Oryginalny opis (EN)

Use when writing, modifying, or reviewing Rust code. ALWAYS invoke before Rust edits; covers Microsoft Pragmatic Rust guidance for error handling, API design, performance, and idiomatic patterns.

Jak działa

  1. Core Principles
  2. Error Handling
  3. API Design
  4. References
Sekcje z nagłówków SKILL.md, w oryginale · 156 linii, 454 słów
Podgląd SKILL.md
---
name: rust-best-practices
description: Use when writing, modifying, or reviewing Rust code. ALWAYS invoke before Rust edits; covers Microsoft Pragmatic Rust guidance for error handling, API design, performance, and idiomatic patterns.
---
# Rust Best Practices

Based on Microsoft Pragmatic Rust Guidelines and Rust community standards.

## Core Principles

1. **Leverage the type system** — Use types to make invalid states unrepresentable
2. **Embrace ownership** — Work with the borrow checker, not against it
3. **Explicit over implicit** — Be clear about fallibility, mutability, and lifetimes
4. **Zero-cost abstractions** — Use iterators, generics, and traits without runtime cost
5. **Fail fast, recover gracefully** — Validate early, handle errors explicitly

---

## Error Handling

### Use `thiserror` for Libraries
```rust
use thiserror::Error;

#[derive(Error, Debug)]
pub enum MyError {
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
    #[error("Parse error at line {line}: {message}")]
    Parse { line: usize, message: String },
    #[error("Not found: {0}")]
    NotFound(String),
}
```

### Use `anyhow` for Applications
```rust
use anyhow::{Context, Result};

fn main() -> Result<()> {
    let config = load_config()
        .context("Failed to load configuration")?;
    run_app(config)?;
    Ok(())
}
```

### Never Panic in Libraries
```rust
// ❌ BAD
pub fn get_item(index: usize) -> &Item {
    &self.items[index]  // Panics on out-of-bounds
}

// ✅ GOOD
pub fn get_item(&self, index: usize) -> Option<&Item> {
    self.items.get(index)
}

// ✅ GOOD - when you need Result
pub fn get_item(&self, index: usize) -> Result<&Item, Error> {
    self.items.get(index).ok_or(Error::NotFound(index))
}
```

---

## API Design

### Use Builder Pattern for Complex Configs
```rust
pub struct Client {
    url: String,
    timeout: Duration,
    retries: u32,
}

impl Client {
    pub fn builder(url: impl Into<String>) -> ClientBuilder {
        ClientBuilder {
            url: url.into(),
            timeout: Duration::from_secs(30),
            retries: 3,
        }
    }
}

pub struct ClientBuilder {
    url: String,
    timeout: Duration,
    retries: u32,
}

impl ClientBuilder {
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    pub fn retries(mut self, retries: u32) -> Self {
        self.retries = retries;
        self
    }

    pub fn build(self) -> Client {
        Client {
            url: self.url,
            timeout: self.timeout,
            retries: self.retries,
        }
    }
}
```

### Use Newtype Pattern
```rust
// ❌ BAD - primitive obsession
fn create_user(name: String, email: String, age: u32) -> User { ... }

// ✅ GOOD - newtype wrappers
pub struct Username(String);
pub struct Email(String);
pub struct Age(u32);

impl Email {
    pub fn new(email: impl Into<String>) -> Result<Self, ValidationError> {
        let email = email.into();
        if email.contains('@') {
            Ok(Self(email))
        } else {
            Err(ValidationError::InvalidEmail)
        }
    }
}

fn create_user(name: Username, email: Email, age: Age) -> User { ... }
```

### Accept `impl Trait` for Flexibility
```rust
// ❌ BAD - overly specific
pub fn process(items: Vec<String>) { ... }

// ✅ GOOD - accept any iterable
pub fn process(items: impl IntoIterator<Item = impl AsRef<str>>) {
    for item in items {
        println!("{}", item.as_ref());
    }
}
```

---

## References

- [Microsoft Pragmatic Rust Guidelines](https://microsoft.github.io/rust-guidelines/)
- [Rust API Guidelines](https://rust-lang.github.io/api-guidelines/)
- [The Rust Book](https://doc.rust-lang.org/book/)
- [references/advanced.md](references/advanced.md) — performance, async, testing, and anti-pattern examples
Pliki w paczce (2)
  • SKILL.md 4 KB
  • references/advanced.md 3 KB

Wersje

RepozytoriumWynikLicencja
Ta strona · majiayu000/spellbook100MIT
crbnos/carbon100AGPL-3.0
sutchan/Agent-Skills-Hub100MIT
randlee/synaptic-canvas100MIT
existential-birds/beagle100Apache-2.0
morganlinton/beautifulrust95MIT

Identyczna treść występuje jeszcze w 1 innych folderach na GitHubie. Tu pokazujemy jedną, najlepiej ocenioną kopię.

Migawka bazy z 28.10.2026 · wersja paczki e3f91aa84b95 (skrót SHA-256 całej paczki)

Pobrania w ostatnich 30 dniach: 0 · ranking

Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.

Podobne skille

  • 100rust
    Podpowiada dobre praktyki Rust przy pisaniu i przeglądzie kodu: struktura, wzorce, wydajność i obsługa błędów.
  • 100rust
    Wskazuje, jak pisać i przeglądać kod Rust zgodnie z wytycznymi stylu, gdy użytkownik o to prosi.
  • 100rust
    Podpowiada konwencje kodowania i dobre praktyki Rust przy każdej pracy z plikami .rs.
  • 100rust-development
    Podpowiada nazewnictwo, typowanie, obsługę błędów i dokumentację w Rust według oficjalnych wytycznych przy pisaniu i refaktoryzacji.
  • 100rust-development
    Rozwija, przegląda i bada kod Rust zgodnie z Pragmatic Rust Guidelines: architekturę, implementację i dokumentację rustdoc.
  • 100rust-backend
    Podaje wytyczne Rust dla backendu Windmill przy każdej zmianie kodu w katalogu backend.

Uwagi i zgłoszenia

Wiadomość trafi do Bartosza Sokolińskiego. Adres e-mail jest potrzebny tylko do odpowiedzi. Szczegóły w polityce prywatności.