Chuyển đến nội dung
Skillpedia
Lập trình chung280k · #242

rust-patterns

Skill này làm gì

Agent này giúp bạn viết code bằng ngôn ngữ Rust theo thực hành tốt nhất. Nó đảm bảo code an toàn, nhanh và dễ bảo trì, bằng cách tập trung vào cách quản lý dữ liệu, xử lý lỗi và cách các phần của code giao tiếp với nhau.

Khi nào nên dùng

  • ✓Khi viết code Rust mới.
  • ✓Khi xem lại code của người khác.
  • ✓Khi tổ chức cấu trúc một dự án Rust.

Liên kết skill

https://github.com/affaan-m/ECC/blob/main/pi/core/skills/rust-patterns/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/rust-patterns/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Làm sao để đảm bảo code Rust của tôi xử lý lỗi an toàn mà không làm chương trình bị sập?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Nó phân tích code Rust của bạn và gợi ý cách dùng các tính năng ngôn ngữ như 'ownership' (quyền sở hữu) và 'borrowing' (mượn) để tránh lỗi phổ biến. Nó cũng hướng dẫn cách xử lý thất bại một cách êm ái bằng 'Result' và '?', và cách tổ chức code bằng 'trait' và 'enum'.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

Rust Development Patterns

Idiomatic Rust patterns and best practices for building safe, performant, and maintainable applications.

When to Use

  • Writing new Rust code
  • Reviewing Rust code
  • Refactoring existing Rust code
  • Designing crate structure and module layout

How It Works

This skill enforces idiomatic Rust conventions across six key areas: ownership and borrowing to prevent data races at compile time, Result/? error propagation with thiserror for libraries and anyhow for applications, enums and exhaustive pattern matching to make illegal states unrepresentable, traits and generics for zero-cost abstraction, safe concurrency via Arc<Mutex<T>>, channels, and async/await, and minimal pub surfaces organized by domain.

Core Principles

1. Ownership and Borrowing

Rust's ownership system prevents data races and memory bugs at compile time.

// Good: Pass references when you don't need ownership
fn process(data: &[u8]) -> usize {
    data.len()
}

// Good: Take ownership only when you need to store or consume
fn store(data: Vec<u8>) -> Record {
    Record { payload: data }
}

// Bad: Cloning unnecessarily to avoid borrow checker
fn process_bad(data: &Vec<u8>) -> usize {
    let cloned = data.clone(); // Wasteful — just borrow
    cloned.len()
}

Use Cow for Flexible Ownership

use std::borrow::Cow;

fn normalize(input: &str) -> Cow<'_, str> {
    if input.contains(' ') {
        Cow::Owned(input.replace(' ', "_"))
    } else {
        Cow::Borrowed(input) // Zero-cost when no mutation needed
    }
}

Error Handling

Use Result and ? — Never unwrap() in Production

// Good: Propagate errors with context
use anyhow::{Context, Result};

fn load_config(path: &str) -> Result<Config> {
    let content = std::fs::read_to_string(path)
        .with_context(|| format!("failed to read config from {path}"))?;
    let config: Config = toml::from_str(&content)
        .with_context(|| format!("failed to parse config from {path}"))?;
    Ok(config)
}

// Bad: Panics on error
fn load_config_bad(path: &str) -> Config {
    let content = std::fs::read_to_string(path).unwrap(); // Panics!
    toml::from_str(&content).unwrap()
}

Library Errors with thiserror, Application Errors with anyhow

// Library code: structured, typed errors
use thiserror::Error;

#[derive(Debug, Error)]
pub enum StorageError {
    #[error("record not found: {id}")]
    NotFound { id: String },
    #[error("connection failed")]
    Connection(#[from] std::io::Error),
    #[error("invalid data: {0}")]
    InvalidData(String),
}

// Application code: flexible error handling
use anyhow::{bail, Result};

fn run() -> Result<()> {
    let config = load_config("app.toml")?;
    if config.workers == 0 {
        bail!("worker count must be > 0");
    }
    Ok(())
}

Option Combinators Over Nested Matching

// Good: Combinator chain
fn find_user_email(users: &[User], id: u64) -> Option<String> {
    users.iter()
        .find(|u| u.id == id)
        .map(|u| u.email.clone())
}

// Bad: Deeply nested matching
fn find_user_email_bad(users: &[User], id: u64) -> Option<String> {
    match users.iter().find(|u| u.id == id) {
        Some(user) => match &user.email {
            email => Some(email.clone()),
        },
        None => None,
    }
}

Enums and Pattern Matching

Model States as Enums

// Good: Impossible states are unrepresentable
enum ConnectionState {
    Disconnected,
    Connecting { attempt: u32 },
    Connected { session_id: String },
    Failed { reason: String, retries: u32 },
}

fn handle(state: &ConnectionState) {
    match state {
        ConnectionState::Disconnected => connect(),
        ConnectionState::Connecting { attempt } if *attempt > 3 => abort(),
        ConnectionState::Connecting { .. } => wait(),
        ConnectionState::Connected { session_id } => use_session(session_id),
        ConnectionState::Failed { retries, .. } if *retries < 5 => retry(),
        ConnectionState::Failed { reason, .. } => log_failure(reason),
    }
}

Exhaustive Matching — No Catch-All for Business Logic

// Good: Handle every variant explicitly
match command {
    Command::Start => start_service(),
    Command::Stop => stop_service(),
    Command::Restart => restart_service(),
    // Adding a new variant forces handling here
}

// Bad: Wildcard hides new variants
match command {

…
Câu hỏi thường gặp

'Ownership' trong Rust là gì?

Đây là hệ thống đảm bảo code an toàn về bộ nhớ, bằng cách xác định ai 'sở hữu' dữ liệu và cách dữ liệu được chia sẻ hoặc chuyển giao, tránh các lỗi thường gặp ở ngôn ngữ khác.

Khác nhau giữa 'thiserror' và 'anyhow' là gì?

'thiserror' dùng trong thư viện để tạo các kiểu lỗi cụ thể, rõ ràng. 'anyhow' linh hoạt hơn và dùng trong ứng dụng để xử lý lỗi đơn giản hơn kèm ngữ cảnh.

Vì sao dùng 'enum' và 'pattern matching'?

Chúng giúp bạn mô hình hóa rõ ràng các trạng thái khác nhau và đảm bảo mọi khả năng đều được xử lý trong code, khiến bạn khó quên xử lý một trường hợp cụ thể.

Chi tiết

Mô tả gốc của tác giả

Idiomatic Rust patterns, ownership, error handling, traits, concurrency, and best practices for building safe, performant applications. Use when writing or reviewing Rust code and ownership, error handling, traits, or concurrency is in question.

repo: affaan-m/ECC

Độ phổ biến

Sao GitHub
280k
Vị trí xếp hạng
#242
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự