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가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
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.
댓글
- …
이 저장소의 다른 스킬
accessibility
280k에이전트가 모든 사람이 쓸 수 있는 인터페이스를 만들도록 돕습니다. 시각 장애나 운동 장애가 있는 사람도 쓸 수 있게 합니다.
agent-architecture-audit
280k에이전트가 모든 것이 올바르게 작동하는지 점검하도록 돕습니다. AI 시스템의 문제를 찾아 고쳐서 기대대로 작동하게 합니다.
agent-eval
280k에이전트가 서로 다른 AI 코딩 도구를 비교하도록 돕습니다. 특정 작업에서 어느 도구가 더 빠르고, 저렴하고, 믿을 만한지 측정합니다.
agent-harness-construction
280k에이전트가 작업을 더 잘 이해하도록 돕습니다. 에이전트가 쓰는 도구와 지시문을 최적화해 성공 가능성을 높입니다.