rust-anti-pattern
Rust 反模式与常见错误。处理代码审查、clone、unwrap、String 用法、迭代器等问题。触发词:anti-pattern, common mistake, clone, unwrap, code review, 代码异味, 常见错误, 代码审查, refactor, 重构
Best use case
rust-anti-pattern is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Rust 反模式与常见错误。处理代码审查、clone、unwrap、String 用法、迭代器等问题。触发词:anti-pattern, common mistake, clone, unwrap, code review, 代码异味, 常见错误, 代码审查, refactor, 重构
Teams using rust-anti-pattern should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/rust-anti-pattern/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How rust-anti-pattern Compares
| Feature / Agent | rust-anti-pattern | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Rust 反模式与常见错误。处理代码审查、clone、unwrap、String 用法、迭代器等问题。触发词:anti-pattern, common mistake, clone, unwrap, code review, 代码异味, 常见错误, 代码审查, refactor, 重构
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# Rust 反模式与常见错误
## 核心问题
**这个模式是否掩盖了设计问题?**
代码能跑不代表代码好。反模式是"能用但不该用"的模式。
---
## Top 5 新手常犯错误
| 排名 | 错误 | 正确做法 |
|-----|------|---------|
| 1 | 用 `.clone()` 躲避借用检查 | 使用引用 |
| 2 | 生产代码用 `.unwrap()` | 用 `?` 或 `with_context()` |
| 3 | 什么都是 `String` | 用 `&str`,必要时用 `Cow<str>` |
| 4 | 索引循环 | 用迭代器 `.iter()`, `.enumerate()` |
| 5 | 与生命周期对抗 | 重新设计数据结构 |
---
## 常见反模式
### 反模式 1:到处 clone
```rust
// ❌ 不好:躲避借用检查
fn process(user: User) {
let name = user.name.clone(); // 为什么需要 clone?
// ...
}
// ✅ 好:直接使用引用
fn process(user: &User) {
let name = &user.name; // 借用即可
}
```
**什么时候真的需要 clone:**
- 确实需要独立副本
- API 设计需要 owned 值
- 数据流向需要
### 反模式 2:生产代码用 unwrap
```rust
// ❌ 不好:可能 panic
let config = File::open("config.json").unwrap();
// ✅ 好:传播错误
let config = File::open("config.json")?;
// ✅ 好:带上下文
let config = File::open("config.json")
.context("failed to open config")?;
```
### 反模式 3:String everywhere
```rust
// ❌ 不好:不必要的分配
fn greet(name: String) {
println!("Hello, {}", name);
}
// ✅ 好:借用即可
fn greet(name: &str) {
println!("Hello, {}", name);
}
// 确实需要 String 的场景:需要持有或修改
```
### 反模式 4:索引循环
```rust
// ❌ 不好:容易出错,效率低
for i in 0..items.len() {
println!("{}: {}", i, items[i]);
}
// ✅ 好:直接迭代
for item in &items {
println!("{}", item);
}
// ✅ 好:需要索引
for (i, item) in items.iter().enumerate() {
println!("{}: {}", i, item);
}
```
### 反模式 5:过度 unsafe
```rust
// ❌ 不好:为了省事用 unsafe
unsafe {
let ptr = data.as_mut_ptr();
// ... 复杂的内存操作
}
// ✅ 好:寻找安全的抽象
let mut data: Vec<u8> = vec![0; size];
// Vec 已经处理了内存管理
```
---
## 代码异味速查
| 现象 | 暗示问题 | 重构方向 |
|-----|---------|---------|
| 很多 `.clone()` | 所有权不清晰 | 明确数据流 |
| 很多 `.unwrap()` | 错误处理缺失 | 添加 Result 处理 |
| 很多 `pub` 字段 | 封装被破坏 | 私有 + 访问器 |
| 深度嵌套 | 逻辑复杂 | 提取方法 |
| 函数过长 (>50行) | 职责过多 | 拆分职责 |
| 巨大的枚举 | 缺少抽象 | Trait + 类型 |
---
## 过时写法 → 现代写法
| 过时 | 现代 |
|-----|------|
| 索引循环 `.items[i]` | `.iter().enumerate()` |
| `collect::<Vec<_>>()` 然后再遍历 | 链式迭代器 |
| `lazy_static!` | `std::sync::OnceLock` |
| `mem::transmute` 转换 | `as` 或 `TryFrom` |
| 自定义链表 | `Vec` 或 `VecDeque` |
| 手动 unsafe cell | `Cell`, `RefCell` |
---
## 代码审查清单
- [ ] 没有无理由的 `.clone()`
- [ ] 库代码没有 `.unwrap()`
- [ ] 没有带不变式的 `pub` 字段
- [ ] 迭代器可用时不使用索引循环
- [ ] `&str` 够用时不使用 `String`
- [ ] 没有忽略 `#[must_use]` 警告
- [ ] `unsafe` 有 SAFETY 注释
- [ ] 没有巨型函数 (>50 行)
---
## 问自己这些问题
1. **这段代码在对抗 Rust 还是在配合 Rust?**
- 对抗 → 重新设计
- 配合 → 继续
2. **这个 clone 是必要的吗?**
- 为了躲避借用 → 错误信号
- 确实需要 → 保留
3. **这个 unwrap 会导致 panic 吗?**
- 可能 → 用 `?`
- 绝不会 → `expect("reason")`
4. **有更 idiomatic 的方式吗?**
- 参考其他 Rust 代码
- 查阅 std 库 APIRelated Skills
settings-ui-patterns
Use when creating or modifying UI components, styling, or visual elements related to Settings in OpenChamber.
responsive-design-patterns
Mobile-first responsive design patterns with breakpoints, fluid layouts, and adaptive components
pattern-extraction
Extract design systems, architecture patterns, and methodology from codebases into reusable skills and documentation. Use when analyzing a project to capture patterns, creating skills from existing code, extracting design tokens, or documenting how a project was built. Triggers on "extract patterns", "extract from this repo", "analyze this codebase", "create skills from this project", "extract design system".
microservices-patterns
Design microservices architectures with service boundaries, event-driven communication, and resilience patterns. Use when building distributed systems, decomposing monoliths, or implementing micros...
MCP Widget Patterns
This skill should be used when the user asks to "design a widget", "what widget pattern should I use", "inline card design", "carousel widget", "fullscreen mode", "picture in picture", "widget layout", "card design for ChatGPT", or needs guidance on specific widget patterns and implementations for OpenAI Apps SDK.
hig-patterns
Apple Human Interface Guidelines interaction and UX patterns.
design-patterns
BK-CI 项目设计模式实践指南,涵盖工厂模式、策略模式、观察者模式、装饰器模式、模板方法等在项目中的实际应用。当用户学习设计模式、重构代码、设计可扩展架构或理解项目设计时使用。
architecture-patterns
Padrões de arquitetura de software - Decisões OBJETIVAS sobre design de sistemas
antiquities-extractor
Extract and structure data from documents about the illegal antiquities trade, including dealers, collectors, artifacts, locations, and relationships. Use when processing news reports, academic articles, legal documents, encyclopedia entries, or research materials pertaining to looted artifacts, antiquities trafficking, provenance research, or cultural heritage crimes. Returns structured JSON with entities (persons, organizations, artifacts, locations) and their relationships.
anticipation-payoff
Use when designing action sequences, gags, reveals, or any motion that needs setup before delivery—preparing audiences for what's coming and maximizing impact.
anticipation-mastery
Use when designing action sequences, user interactions, state transitions, or any motion that needs telegraphing to feel intentional rather than sudden.
---name: antibody-design-agent
description: An advanced agent for de novo antibody design and optimization using state-of-the-art protein language models (MAGE, RFdiffusion).