rust-safety

A guide to writing Rust code around ownership, borrowing, error results, and carefully limited unsafe code.

In plain words
What is it for?
Use it when designing Rust data structures, fixing borrow-checker errors, writing libraries, handling failures, or deciding whether unsafe code is needed.
Why use it?
It helps preserve Rust’s compile-time safety instead of hiding design problems with unnecessary cloning, shared ownership, or runtime panics.

Skill for Claude CodeCodex

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add skills/wade-devcode/awesome-coding-skills-cn/rust-safety
Any agent
npx skills add Wade-DevCode/awesome-coding-skills-cn --skill rust-safety
Clone the repo
git clone --depth 1 https://github.com/Wade-DevCode/awesome-coding-skills-cn

Made for: Claude Code, Codex.

Per session 20 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 2,400 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00020 $0.02400
Opus 5 $0.00010 $0.01200
Sonnet 5 $0.00004 $0.00480
Haiku 4.5 $0.00002 $0.00240

Measured 2d ago against content hash 6db4e7ed0d84, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

rust-safety scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 2d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

skills/rust-safety/SKILL.md · 160 lines

How it starts

The opening of the file, as written. The whole thing — 160 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Rust 安全实践

何时用

  • 写新的 Rust 函数、结构体或模块时。
  • 设计数据结构,思考所有权与生命周期时。
  • 处理错误传播、编写库 crate 时。
  • 准备写 unsafe 块或评估是否真的需要 unsafe 时。
  • 发现编译器报 borrow checker 错误,想靠 clone/Rc 强行绕过时。

核心规则

1. 顺着所有权/借用设计,不靠 clone/Rc 硬绕;理解生命周期

规则: 遇到借用检查报错时,先理解所有权模型要表达的约束,调整数据流或函数签名;只有在语义上确实需要共享所有权时才用 Rc/Arc,不把它们当"绕过编译器的万金油";clone 有性能代价,大结构体不随意 clone

为什么: AI 面对 borrow checker 报错时最常见的反应是加 .clone() 或把类型换成 Rc<RefCell<T>>——这能让代码编译,但往往意味着绕开了编译器在帮你捕获的真实问题:可能是数据所有权设计不合理,可能是生命周期标注缺失。用 RefCell 把静态借用检查变成运行时 panic,在 Rust 里是倒退,不是进步。

怎么做:

  • 报 borrow 错误 → 先读错误信息,理解哪个变量的生命周期冲突,考虑重组代码顺序或拆分函数。
  • 函数返回引用 → 正确标注生命周期参数,让编译器而非运行时来保证安全。
  • 确实需要多所有者 → Arc<T>(多线程)或 Rc<T>(单线程),但要在注释里说明为何需要共享所有权。

2. 错误用 Result + ?,库代码不 unwrap/panic;用 thiserror/anyhow 分场景

规则: 可能失败的操作返回 Result<T, E>,通过 ? 传播;库 crate 的公开 API 中不使用 unwrap()/expect()/panic!()(调用方无法捕获 panic);应用程序层用 anyhow 简化错误汇聚,库层用 thiserror 定义具体错误类型。

为什么: AI 写 Rust 时的典型懒惰:let val = map.get("key").unwrap(),在 happy path 下工作,一旦 key 不存在就 unwind panic,且调用方无法在类型层面知道这里会 panic。库的职责是把所有可能的失败都表达在类型里,让调用方决定怎么处理,而不是替调用方决定"遇到这种情况就崩溃"。

怎么做:

  • 库 crate:#[derive(thiserror::Error)] 定义枚举错误类型,每个变体对应一种具体失败场景。
  • 应用 crate / 原型:anyhow::Result<T> + ? 快速传播,context()/with_context() 添加现场信息。
  • 确实不可能失败的 unwrap → 改写成 expect("此处 key 在初始化时已保证存在") 并写明原因,或用 unreachable! 配合注释。

3. unsafe 最小化并注释不变量;能安全抽象就封装

规则: unsafe 块应尽可能小,仅包含无法用安全 API 表达的操作;每个 unsafe 块旁必须有注释,说明为何此处安全(维护的不变量是什么);能把 unsafe 封装进一个安全的函数/结构体,就不要让 unsafe 泄漏到上层调用方。

为什么: AI 倾向于在遇到生命周期或类型系统挑战时直接用 unsafe 强行转换(如 std::mem::transmute),注释一句"// 应该没问题"就提交了。这类代码的危险性在于它能编译、能通过测试,但在某个边界条件下触发未定义行为,且 Miri / sanitizer 很难覆盖到所有路径。

怎么做:

  • unsafe 前先问:有没有 std/bytemuck/zerocopy 等安全 crate 能做这件事?
  • 写了 unsafe → 注释格式:// SAFETY: [解释为何此处满足 XX 的不变量,即...]
  • miricargo miri test)定期跑,检测未定义行为;CI 里加 cargo test --sanitize=address

4. 用类型表达约束(枚举状态机、newtype),让非法状态不可表示

规则: 把业务约束编码进类型系统:用枚举而非字符串/整数常量表示状态;用 newtype 模式区分语义不同的同类型值;避免用 bool 参数区分行为——该拆成两个函数。

Read the full file on GitHub · 160 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 2d ago First seen · 160 lines · 20 tokens per session scan A 6db4e7ed0d84

Subscribe to this mod's changes

rust-safety is a skill published in the GitHub repository Wade-DevCode/awesome-coding-skills-cn (6 stars, last pushed 2mo ago), licensed MIT. It adds 20 tokens to every session and 2,400 once invoked, about $0.0001 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-31.

Related

Other skills, from other repositories

chinese-documentation

中文文档排版参考——中英文空格、全半角标点、术语保留、链接格式、中文文案排版指北约定。仅在用户显式 /chinese-documentation 时调用,不要根据上下文自动触发。.

jnMetaCode/superpowers-zh · 62 tokens

chinese-git-workflow

国内 Git 平台配置参考——Gitee、Coding.net、极狐 GitLab、CNB 的 SSH/HTTPS/凭据/CI 接入差异与镜像同步配置。仅在用户显式 /chinese-git-workflow 时调用,不要根据上下文自动触发。.

jnMetaCode/superpowers-zh · 69 tokens

brainstorming

在任何创造性工作之前必须使用此技能——创建功能、构建组件、添加功能或修改行为。在实现之前先探索用户意图、需求和设计。.

jnMetaCode/superpowers-zh · 40 tokens

chinese-code-review

中文 review 沟通参考——话术模板、分级标注(必须修复/建议修改/仅供参考)、国内团队常见反模式应对。仅在用户显式 /chinese-code-review 时调用,不要根据上下文自动触发。.

jnMetaCode/superpowers-zh · 62 tokens

chinese-commit-conventions

中文 commit 与 changelog 配置参考——Conventional Commits 中文适配、commitlint/husky/commitizen 中文模板、conventional-changelog 中文配置。仅在用户显式 /chinese-commit-conventions 时调用,不要根据上下文自动触发。.

jnMetaCode/superpowers-zh · 65 tokens

mcp-builder

MCP 服务器构建方法论 — 系统化构建生产级 MCP 工具,让 AI 助手连接外部能力.

jnMetaCode/superpowers-zh · 32 tokens