rust
하는 일
이 가이드는 효율적이고 관용적인 Rust 코드를 작성하기 위한 모범 사례를 제공합니다. '소유권'과 '빌림' 같은 언어 기능을 올바르게 사용하고, 오류를 견고하게 처리하며, 이터레이터와 패턴 매칭을 효과적으로 활용하는 방법을 가르칩니다.
사용하는 경우
- ✓Rust의 기본 개념을 배울 때.
- ✓더 나은 효율을 위해 기존 Rust 코드를 리팩터링할 때.
- ✓흔한 Rust 오류를 디버깅하는 경우.
스킬 링크
https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/rust/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“Rust에서 불필요한 데이터 복제를 어떻게 피할 수 있나요?”
매주 새 스킬 5개. 읽는 데 1분.
작동 방식
AI는 '나쁜' 코드 예시와 좋은 Rust 코드 예시를 비교합니다. 복사본(`String`)보다 참조(`&str`)를 선호하고 오류 처리에 `?` 연산자를 사용하는 등, 모범 사례 뒤의 원칙을 설명합니다.
기술 내용 (원본 SKILL.md)
작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.
Rust: Idiomatic Efficiency Reference
When to Use
- Use this skill when the task matches this description: Language-specific super-code guidelines for rust.
Table of Contents
- Ownership & Borrowing
- Error Handling
- Iterators
- Pattern Matching
- Structs & Enums
- Concurrency
- Anti-patterns specific to Rust
1. Ownership & Borrowing {#ownership}
// ❌ Cloning to avoid thinking about lifetimes
fn get_name(user: &User) -> String {
user.name.clone()
}
// ✅ — return a reference when the data lives long enough
fn get_name(user: &User) -> &str {
&user.name
}
// ❌ Taking ownership when borrowing suffices
fn print_name(name: String) {
println!("{name}");
}
// ✅
fn print_name(name: &str) {
println!("{name}");
}
// ❌ Unnecessary .to_string() / .to_owned() in hot paths
let key = id.to_string();
map.get(&key)
// ✅ — use Borrow trait; HashMap<String, V> accepts &str as key
map.get(id)
Prefer &str over String in function parameters unless the function needs to own the data.
2. Error Handling {#errors}
// ❌ .unwrap() in production code
let file = File::open(path).unwrap();
// ✅
let file = File::open(path)
.map_err(|e| AppError::Io { path: path.to_owned(), source: e })?;
// ❌ Manual match on Result for every call
match do_thing() {
Ok(v) => v,
Err(e) => return Err(e),
}
// ✅ — the ? operator
let v = do_thing()?;
// ❌ Box<dyn Error> everywhere (loses type info)
fn run() -> Result<(), Box<dyn std::error::Error>> { ... }
// ✅ — use thiserror for library errors, anyhow for application errors
use anyhow::{Context, Result};
fn run() -> Result<()> {
do_thing().context("failed during run")?;
Ok(())
}
// ❌ Separate error enum variant for every call site
enum Error { FileOpen, FileRead, Parse, Network, ... }
// ✅ — use thiserror with #[from] for automatic conversion
#[derive(thiserror::Error, Debug)]
enum Error {
#[error("io error")] Io(#[from] std::io::Error),
#[error("parse error")] Parse(#[from] serde_json::Error),
}
3. Iterators {#iterators}
// ❌ Imperative accumulation
let mut result = Vec::new();
for item in &items {
if item.active {
result.push(item.name.to_uppercase());
}
}
// ✅
let result: Vec<_> = items.iter()
.filter(|i| i.active)
.map(|i| i.name.to_uppercase())
.collect();
// ❌ Manual sum
let mut total = 0;
for order in &orders { total += order.amount; }
// ✅
let total: u64 = orders.iter().map(|o| o.amount).sum();
// ❌ Index-based loop
for i in 0..items.len() {
process(&items[i]);
}
// ✅
for item in &items {
process(item);
}
// With index:
for (i, item) in items.iter().enumerate() {
process(i, item);
}
Chain iterators lazily; only .collect() when you actually need a concrete collection.
4. Pattern Matching {#patterns}
// ❌ if-let chain that should be match
if let Some(x) = opt {
if x > 0 {
use(x)
}
}
// ✅
if let Some(x) = opt.filter(|&x| x > 0) {
use(x)
}
// or match with guard:
match opt {
Some(x) if x > 0 => use(x),
_ => {}
}
// ❌ match with identical arms
match status {
Status::Active => true,
Status::Pending => true,
Status::Inactive => false,
}
// ✅
matches!(status, Status::Active | Status::Pending)
// ❌ Destructuring in body instead of pattern
fn area(shape: &Shape) -> f64 {
match shape {
Shape::Circle(c) => { let r = c.radius; r * r * PI }
Shape::Rect(r) => { let w = r.width; let h = r.height; w * h }
}
}
// ✅ — destructure in pattern
match shape {
Shape::Circle(Circle { radius, .. }) => radius * radius * PI,
Shape::Rect(Rect { width, height }) => width * height,
}
5. Structs & Enums {#structs}
// ❌ Enum variant carrying bool for binary state
enum State { Running(bool) } // true = paused?
// ✅ — explicit variants
enum State { Running, Paused, Stopped }
// ❌ Struct with many Option fields (stringly optional)
struct Config {
timeout: Option<u64>,
retries: Option<u32>,
base_url: Option<String>,
}
// ✅ — use Default + builder pattern or #[derive(Default)] with sensible defaults
#[derive(Default)]
struct Config {
timeout: u64, // default 0 = no timeout
…
자주 묻는 질문
'소유권'과 '빌림'이란 무엇인가요?
'소유권'은 Rust가 메모리를 관리하는 방식으로, 모든 값에는 소유자가 있습니다. '빌림'은 소유권을 넘기지 않고 값에 대한 접근을 잠시 빌려주는 것입니다.
Rust에서 `.unwrap()`은 왜 피해야 하나요?
값이 예상과 다르면 `.unwrap()`은 프로그램이 예기치 않게 중단되게 할 수 있습니다. 안전한 오류 처리를 위해 `?` 연산자나 `match`를 쓰는 것이 낫습니다.
Rust의 이터레이터란 무엇인가요?
데이터 모음을 효율적으로 처리하는 방법입니다. 요소를 필터링하거나 매핑하는 작업을 이어서 하고, 마지막에 결과를 모을 수 있습니다.
상세 정보
인기도
- GitHub 스타
- 48k
- 순위
- #5898
- 라이선스
- MIT
- 업데이트
- 2026. 10. 15.
댓글
- …
이 저장소의 다른 스킬
00-andruia-consultant
48k에이전트가 AI 프로젝트를 시작하거나 개선할 수 있도록 코드를 분석하고 스페인어로 실행 계획을 세워 줍니다.
007
48k에이전트가 보안 감사와 위협 모델링을 수행해 공격과 취약점으로부터 프로젝트를 보호하도록 돕습니다.
10-andruia-skill-smith
48k에이전트가 AI 도구의 작동 방식을 정의하고 문서를 쓰며 구조를 검증하도록 돕습니다.
20-andruia-niche-intelligence
48k에이전트가 신뢰할 수 있는 자료를 바탕으로 특정 산업의 맥락, 규칙, 사용 패턴, 위험을 정리한 요약을 만들도록 돕습니다.