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

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가 스킬을 읽고 지침을 따릅니다.

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

Use this skill to help me: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/rust/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분.

작동 방식

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

  1. Ownership & Borrowing
  2. Error Handling
  3. Iterators
  4. Pattern Matching
  5. Structs & Enums
  6. Concurrency
  7. 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의 이터레이터란 무엇인가요?

데이터 모음을 효율적으로 처리하는 방법입니다. 요소를 필터링하거나 매핑하는 작업을 이어서 하고, 마지막에 결과를 모을 수 있습니다.

상세 정보

작성자의 원본 설명

Language-specific super-code guidelines for rust.

repo: sickn33/agentic-awesome-skills

인기도

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

이 스킬이 유용한가요?

0

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

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬