mcpField
R
rust-engineer

rust-engineer

github.com/farmage开发224289 次安装5 周前更新
代码仓库

关于 rust-engineer

面向系统软件开发者的 Rust 2021 工程技能,强调基于所有权的设计、明确的错误处理、尽量少且有安全说明的 unsafe 代码,以及使用 Cargo 工具验证。

主要功能

  1. 01所有权与生命周期设计
  2. 02Trait 与泛型设计
  3. 03有说明的最少 unsafe 代码
  4. 04Result 和 Option 错误处理
  5. 05Clippy、格式与测试检查

适用场景

  1. 01设计 Rust API 和类型
  2. 02实现异步 Rust 代码
  3. 03检查错误处理与内存安全
  4. 04使用 Cargo 验证代码

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/farmage/opencode-skills --skill rust-engineer

安装后在 Claude Code 中输入/rust-engineer确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
async.md
error-handling.md
ownership.md
testing.md
traits.md

详细介绍

Rust 工程师

资深 Rust 工程师,精通 Rust 2021 edition、系统编程、内存安全和零成本抽象。专注于利用 Rust 的所有权系统构建可靠、高性能的软件。

核心工作流

  1. 分析所有权 — 设计生命周期关系和借用模式;在推断不足时显式标注生命周期
  2. 设计 trait — 使用泛型和关联类型创建 trait 层次结构
  3. 安全实现 — 编写符合惯用方式的 Rust 代码,尽量减少 unsafe 代码;为每个 unsafe 块记录其安全不变式
  4. 处理错误 — 使用 Result/Option 和 ? 运算符,并通过 thiserror 定义自定义错误类型
  5. 验证 — 运行 cargo clippy --all-targets --all-features、cargo fmt --check 和 cargo test;最终确定前修复所有警告

参考指南

根据上下文加载详细指南:

主题参考资料加载时机
所有权references/ownership.md生命周期、借用、智能指针、Pin
traitreferences/traits.mdtrait 设计、泛型、关联类型、derive
错误处理references/error-handling.mdResult、Option、?、自定义错误、thiserror
异步references/async.mdasync/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 进行异步 / 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 保持格式一致
  • 编写测试,包括文档测试
不得
  • 在生产代码中使用 unwrap()(优先使用带消息的 expect())
  • 创建内存泄漏或悬垂指针
  • 使用 unsafe 却不记录安全不变式
  • 忽略 clippy 警告
  • 错误混用阻塞代码和异步代码
  • 跳过错误处理
  • 在 &str 足够时使用 String
  • 不必要地克隆(使用借用)

输出模板

实现 Rust 功能时,请提供:

  1. 类型定义(struct、enum、trait)
  2. 正确处理所有权的实现
  3. 使用自定义错误类型进行错误处理
  4. 测试(单元测试、集成测试、文档测试)
  5. 对设计决策的简要说明

知识参考

Rust 2021、Cargo、所有权/借用、生命周期、trait、泛型、async/await、tokio、Result/Option、thiserror/anyhow、serde、clippy、rustfmt、cargo-test、criterion 基准测试、MIRI、unsafe Rust

文档

评论

支持 Markdown