본문으로 건너뛰기
Skillpedia
일반 코딩280k · #242

rust-patterns

하는 일

이 에이전트는 모범 사례를 따라 Rust 언어로 코드를 작성하도록 돕습니다. 데이터를 어떻게 관리하고, 오류를 어떻게 처리하며, 코드의 부분들이 어떻게 통신하는지에 집중해 코드가 안전하고, 빠르고, 유지보수하기 쉽도록 합니다.

사용하는 경우

  • ✓새 Rust 코드를 작성할 때.
  • ✓다른 사람의 코드를 검토할 때.
  • ✓Rust 프로젝트의 구조를 정리할 때.

스킬 링크

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

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/rust-patterns/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“Rust 코드가 프로그램을 멈추지 않고 오류를 안전하게 처리하도록 하려면 어떻게 해야 할까요?”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

Rust 코드를 분석하고, ‘소유권’과 ‘차용’ 같은 언어 기능을 사용해 흔한 버그를 막는 방법을 제안합니다. 또한 ‘Result’와 ‘?’를 사용해 실패를 우아하게 처리하고, ‘트레이트’와 ‘열거형’으로 코드를 구성하는 방법을 안내합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

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 {

…
자주 묻는 질문

Rust의 ‘소유권’이란 무엇인가요?

데이터의 ‘소유자’를 정하고, 데이터를 어떻게 공유하거나 넘길 수 있는지 정하는 시스템입니다. 다른 언어에서 흔한 메모리 버그를 막아 줍니다.

‘thiserror’와 ‘anyhow’의 차이는 무엇인가요?

‘thiserror’는 라이브러리에서 구체적이고 명확한 오류 타입을 만들 때 사용합니다. ‘anyhow’는 더 유연해서, 애플리케이션에서 간단하고 문맥이 있는 오류 처리를 할 때 사용합니다.

‘열거형’과 ‘패턴 매칭’을 쓰는 이유는 무엇인가요?

여러 상태를 명확하게 모델링하고, 모든 경우가 처리되도록 보장할 수 있습니다. 특정 경우를 빠뜨리기 어렵게 만듭니다.

상세 정보

작성자의 원본 설명

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

인기도

GitHub 스타
280k
순위
#242
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬