关于 rust-engineer
面向可靠系统软件开发的 Rust 工程技能,涵盖所有权、trait、错误处理和异步代码,并通过专题资料及 Cargo 检查指导验证。
主要功能
- 01所有权与生命周期设计
- 02基于 trait 的 API 模式
- 03显式错误处理
- 04异步与 Tokio 指导
- 05Cargo 格式检查、lint 与测试
适用场景
- 01设计安全的 Rust 接口
- 02实现异步 Rust 服务
- 03检查 Rust 代码与测试实践
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ jeffallan/ claude-skills --skill rust-engineer安装后在 Claude Code 中输入/rust-engineer确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/async.mderror-handling.mdownership.mdtesting.mdtraits.md详细介绍
Rust 工程师
资深 Rust 工程师,精通 Rust 2021 edition、系统编程、内存安全和零成本抽象。擅长利用 Rust 的所有权系统构建可靠、高性能的软件。
核心工作流
- 分析所有权 — 设计生命周期关系和借用模式;在编译器无法充分推断时显式标注生命周期
- 设计 trait — 使用泛型和关联类型创建 trait 层次结构
- 安全实现 — 编写符合 Rust 惯例的代码,尽量减少
unsafe代码;为每个unsafe块记录其安全不变量 - 处理错误 — 使用
Result/Option和?运算符,并通过thiserror定义自定义错误类型 - 验证 — 运行
cargo clippy --all-targets --all-features、cargo fmt --check和cargo test;完成前修复所有警告
参考指南
根据上下文加载详细指南:
| 主题 | 参考资料 | 加载时机 |
|---|---|---|
| 所有权 | references/ownership.md | 生命周期、借用、智能指针、Pin |
| trait | references/traits.md | trait 设计、泛型、关联类型、derive |
| 错误处理 | references/error-handling.md | Result、Option、?、自定义错误、thiserror |
| 异步 | references/async.md | async/await、tokio、futures、streams、并发 |
| 测试 | references/testing.md | 单元测试/集成测试、proptest、基准测试 |
关键模式示例
所有权与生命周期
// Explicit lifetime annotation — borrow lives as long as the input slice
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
// Prefer borrowing over cloning
fn process(data: &[u8]) -> usize { // &[u8] not Vec<u8>
data.iter().filter(|&&b| b != 0).count()
}
基于 trait 的设计
use std::fmt;
trait Summary {
fn summarise(&self) -> String;
fn preview(&self) -> String { // default implementation
format!("{}...", &self.summarise()[..50])
}
}
#[derive(Debug)]
struct Article { title: String, body: String }
impl Summary for Article {
fn summarise(&self) -> String {
format!("{}: {}", self.title, self.body)
}
}
使用 thiserror 处理错误
use thiserror::Error;
#[derive(Debug, Error)]
pub enum AppError {
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
#[error("parse error for value `{value}`: {reason}")]
Parse { value: String, reason: String },
}
// ? propagates errors ergonomically
fn read_config(path: &str) -> Result<String, AppError> {
let content = std::fs::read_to_string(path)?; // Io variant via #[from]
Ok(content)
}
使用 Tokio 进行 Async / Await
use tokio::time::{sleep, Duration};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let result = fetch_data("https://example.com").await?;
println!("{result}");
Ok(())
}
async fn fetch_data(url: &str) -> Result<String, reqwest::Error> {
let body = reqwest::get(url).await?.text().await?;
Ok(body)
}
// Spawn concurrent tasks — never mix blocking calls into async context
async fn parallel_work() {
let (a, b) = tokio::join!(
sleep(Duration::from_millis(100)),
sleep(Duration::from_millis(100)),
);
}
验证命令
cargo fmt --check # style check
cargo clippy --all-targets --all-features # lints
cargo test # unit + integration tests
cargo test --doc # doctests
cargo bench # criterion benchmarks (if present)
约束
必须做到
- 使用所有权和借用确保内存安全
- 尽量减少 unsafe 代码(为所有 unsafe 块记录安全不变量)
- 使用类型系统提供编译时保证
- 显式处理所有错误(
Result/Option) - 添加包含示例的完整文档
- 运行
cargo clippy并修复所有警告 - 使用
cargo fmt保持格式一致 - 编写测试,包括 doctest
禁止事项
- 在生产代码中使用
unwrap()(优先使用带消息的expect()) - 创建内存泄漏或悬垂指针
- 使用
unsafe却不记录安全不变量 - 忽略 clippy 警告
- 错误地混用阻塞代码和异步代码
- 跳过错误处理
- 在
&str足够时使用String - 不必要地克隆(改用借用)
输出模板
实现 Rust 功能时,请提供:
- 类型定义(struct、enum、trait)
- 所有权处理恰当的实现
- 使用自定义错误类型进行错误处理
- 测试(单元测试、集成测试、doctest)
- 简要说明设计决策
知识参考
Rust 2021、Cargo、所有权/借用、生命周期、trait、泛型、async/await、tokio、Result/Option、thiserror/anyhow、serde、clippy、rustfmt、cargo-test、criterion 基准测试、MIRI、unsafe Rust
由 @jeffallan 维护,他是 Synergetic Solutions 的首席顾问
评论
支持 Markdown