Token导航 LogoToken导航TokenDH.com
研究检索需要联网github未标认证来源可访问许可证需确认审计通过

rust-anti-patternRust anti pattern 搜索

Agent Skill

rust-anti-pattern 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

324

周安装

13

GitHub Stars

29

下载量

105
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:rust-anti-pattern(Rust anti pattern 搜索)
来源仓库:https://github.com/huiali/rust-skills
仓库路径:skills/rust-anti-pattern
安装命令:
npx skills add https://github.com/huiali/rust-skills --skill rust-anti-pattern
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/huiali/rust-skills --skill rust-anti-pattern

简介

用于查找、检索和筛选相关信息。rust-anti-pattern 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

  • 适合根据关键词、任务场景或来源线索快速定位候选结果。
  • 可结合来源仓库和原始 README 核验具体用法。
  • 安装前建议确认权限范围和维护状态。
  • 注意是否会触发联网、命令执行或文件读写。

SKILL.md

Top 5 Beginner Mistakes

RankMistakeCorrect Approach
1Using .clone() to escape borrow checkerUse references
2Using .unwrap() in production codeUse ? or with_context()
3Everything is StringUse &str, Cow<str> when needed
4Index-based loopsUse iterators .iter(), .enumerate()
5Fighting lifetimesRedesign data structure

Common Anti-Patterns

Anti-Pattern 1: Clone Everywhere

// ❌ Bad: escaping borrow checker
fn process(user: User) {
    let name = user.name.clone();  // Why clone?
    // ...
}

// ✅ Good: use references
fn process(user: &User) {
    let name = &user.name;  // Just borrow
}

When clone is actually needed:

  • Truly need independent copy
  • API design requires owned value
  • Data flow requirements

Anti-Pattern 2: Unwrap in Production

// ❌ Bad: may panic
let config = File::open("config.json").unwrap();

// ✅ Good: propagate error
let config = File::open("config.json")?;

// ✅ Good: with context
let config = File::open("config.json")
    .context("failed to open config")?;

Anti-Pattern 3: String Everywhere

// ❌ Bad: unnecessary allocation
fn greet(name: String) {
    println!("Hello, {}", name);
}

// ✅ Good: borrow is enough
fn greet(name: &str) {
    println!("Hello, {}", name);
}

// When String is actually needed: ownership or mutation required

Anti-Pattern 4: Index Loops

// ❌ Bad: error-prone, inefficient
for i in 0..items.len() {
    println!("{}: {}", i, items[i]);
}

// ✅ Good: direct iteration
for item in &items {
    println!("{}", item);
}

// ✅ Good: with index
for (i, item) in items.iter().enumerate() {
    println!("{}: {}", i, item);
}

Anti-Pattern 5: Excessive Unsafe

// ❌ Bad: unsafe for convenience
unsafe {
    let ptr = data.as_mut_ptr();
    // ... complex memory operations
}

// ✅ Good: find safe abstractions
let mut data: Vec<u8> = vec![0; size];
// Vec handles memory management

Solution Patterns

Pattern 1: Avoiding Clone

// ❌ Anti-pattern: clone to satisfy borrow checker
fn process_data(data: &Data) -> String {
    let cloned = data.items.clone();
    cloned.into_iter().map(|x| x.to_string()).collect()
}

// ✅ Solution: use references properly
fn process_data(data: &Data) -> String {
    data.items.iter().map(|x| x.to_string()).collect()
}

Pattern 2: Proper Error Handling

// ❌ Anti-pattern: unwrap chain
fn load_config() -> Config {
    let content = std::fs::read_to_string("config.toml").unwrap();
    toml::from_str(&content).unwrap()
}

// ✅ Solution: Result propagation
fn load_config() -> Result<Config, Box<dyn Error>> {
    let content = std::fs::read_to_string("config.toml")?;
    Ok(toml::from_str(&content)?)
}

// ✅ Solution: with context (anyhow)
fn load_config() -> anyhow::Result<Config> {
    let content = std::fs::read_to_string("config.toml")
        .context("failed to read config file")?;
    toml::from_str(&content)
        .context("failed to parse config")
}

Pattern 3: String vs &str

// ❌ Anti-pattern: String parameters everywhere
struct Config {
    host: String,
    port: String,
    path: String,
}

impl Config {
    fn new(host: String, port: String, path: String) -> Self {
        Self { host, port, path }
    }
}

// ✅ Solution: accept &str, store String
impl Config {
    fn new(host: impl Into<String>, port: u16, path: impl Into<String>) -> Self {
        Self {
            host: host.into(),
            port: port.to_string(),
            path: path.into(),
        }
    }
}

Pattern 4: Iterator-Based Processing

// ❌ Anti-pattern: manual indexing
fn sum_even(nums: &[i32]) -> i32 {
    let mut sum = 0;
    for i in 0..nums.len() {
        if nums[i] % 2 == 0 {
            sum += nums[i];
        }
    }
    sum
}

// ✅ Solution: iterator chain
fn sum_even(nums: &[i32]) -> i32 {
    nums.iter()
        .filter(|&&n| n % 2 == 0)
        .sum()
}

Code Smell Quick Reference

SymptomIndicatesRefactoring Direction
Many .clone()Unclear ownershipClarify data flow
Many .unwrap()Missing error handlingAdd Result handling
Many pub fieldsBroken encapsulationPrivate + accessors
Deep nestingComplex logicExtract methods
Long functions (>50 lines)Too many responsibilitiesSplit responsibilities
Huge enumsMissing abstractionTrait + types

Outdated → Modern Patterns

OutdatedModern
Index loop .items[i].iter().enumerate()
collect::<Vec<_>>() then iterateChain iterators
lazy_static!std::sync::OnceLock
mem::transmute conversionas or TryFrom
Custom linked listVec or VecDeque
Manual unsafe cellCell, RefCell

Workflow

Step 1: Identify Anti-Patterns

Code review checklist:
  → Lots of .clone()? Check ownership design
  → .unwrap() in lib code? Need error handling
  → Index loops? Should use iterators
  → pub fields with invariants? Need encapsulation
  → >50 line functions? Should split

Step 2: Ask Key Questions

1. Is this fighting Rust or working with Rust?
   Fighting → Redesign
   Working with → Continue

2. Is this clone necessary?
   Escaping borrow checker → Warning sign
   Actually need copy → Keep

3. Will this unwrap panic?
   Might panic → Use ?
   Never panics → expect("reason")

4. Is there a more idiomatic way?
   Check std library patterns
   Review other Rust code

Step 3: Refactor

Identified anti-pattern?
  ↓
Understand the root cause
  ↓
Find idiomatic alternative
  ↓
Refactor incrementally
  ↓
Test thoroughly

Review Checklist

When reviewing code:

  • No unreasonable .clone()
  • Library code has no .unwrap()
  • No pub fields with invariants
  • No index loops when iterators available
  • Using &str instead of String when sufficient
  • Not ignoring #[must_use] warnings
  • unsafe has SAFETY comments
  • No giant functions (>50 lines)
  • Error handling uses Result not panic
  • No premature optimization

Verification Commands

# Check for common issues
cargo clippy

# Specific anti-pattern lints
cargo clippy -- -W clippy::clone_on_copy \
                -W clippy::unwrap_used \
                -W clippy::expect_used

# Check for complexity
cargo clippy -- -W clippy::cognitive_complexity

# Find todos and fixmes
rg "TODO|FIXME|XXX|HACK" --type rust

Common Pitfalls

1. Clone to Compile

Symptom: Lots of .clone() calls

// ❌ Bad: cloning to satisfy compiler
fn process(items: &Vec<Item>) -> Vec<String> {
    let items_clone = items.clone();
    items_clone.into_iter().map(|i| i.name).collect()
}

// ✅ Good: proper borrowing
fn process(items: &[Item]) -> Vec<String> {
    items.iter().map(|i| i.name.clone()).collect()
}

// ✅ Better: no clone at all
fn process(items: &[Item]) -> Vec<&str> {
    items.iter().map(|i| i.name.as_str()).collect()
}

2. Error Handling Shortcuts

Symptom: Unwrap/expect in production code

// ❌ Bad: panic on error
let data = fetch_data().unwrap();
let parsed: Config = serde_json::from_str(&data).expect("bad JSON");

// ✅ Good: proper error propagation
fn load_data() -> Result<Config, Box<dyn Error>> {
    let data = fetch_data()?;
    let parsed = serde_json::from_str(&data)?;
    Ok(parsed)
}

3. String Allocation Waste

Symptom: Unnecessary String allocations

// ❌ Bad: allocating for no reason
fn log_message(level: String, msg: String) {
    println!("[{}] {}", level, msg);
}

// ✅ Good: borrow when possible
fn log_message(level: &str, msg: &str) {
    println!("[{}] {}", level, msg);
}

Self-Check Questions

1. Is this code fighting Rust?

  • Fighting → Redesign approach
  • Working with → Continue

2. Is this clone necessary?

  • To escape borrow checker → Warning sign
  • Actually need independent copy → OK

3. Will this unwrap panic?

  • Might panic → Use ?
  • Never panics → expect("reason")

4. Is there a more idiomatic way?

  • Reference other Rust codebases
  • Check std library APIs

Related Skills

  • rust-coding - Idiomatic patterns to follow
  • rust-ownership - Understanding borrowing to avoid clones
  • rust-error - Proper error handling patterns
  • rust-performance - When optimization matters
  • rust-refactoring - Systematic code improvement

Localized Reference

  • Chinese version: SKILL_ZH.md - 完整中文版本,包含所有内容

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

34.75%
按下载量换算36

Claude

28.71%
按下载量换算30

Cursor

19.37%
按下载量换算20

Gemini CLI

9.43%
按下载量换算10

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills