news 2026/9/12 4:18:51

agents24 Rust 项目脚手架实战:用 `/systems-programming:rust-project` 一键生成生产级 Cargo 工程

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
agents24 Rust 项目脚手架实战:用 `/systems-programming:rust-project` 一键生成生产级 Cargo 工程

agents24 Rust 项目脚手架实战:用/systems-programming:rust-project一键生成生产级 Cargo 工程

【免费下载链接】agentsMulti-harness agentic plugin marketplace for Claude Code, Codex, Cursor, OpenCode, GitHub Copilot, and Google Antigravity项目地址: https://gitcode.com/GitHub_Trending/agents24/agents

导读

在 agents24 多 Harness Agent 插件市场中,rust-project.md 是一条专注于Rust 项目脚手架生成的 Slash 命令:它以自然语言描述为输入,自动分析项目形态(二进制工具、库、工作区、Web API、WebAssembly),并产出符合 Rust 惯例的完整工程结构、Cargo.toml配置、模块组织、测试体系与开发工具链。阅读本文后,你将掌握该命令的五类项目类型判定方法、从cargo new到生产配置的完整落地步骤,以及如何与rust-proAgent、rust-async-patternsSkill 联动,把一次脚手架调用升级为类型安全、错误处理规范、异步模型正确的可运行工程。

命令定位:项目脚手架三件套之一

在 docs/usage.md 的"Project Scaffolding"命令分类中,/systems-programming:rust-project/python-development:python-scaffold/javascript-typescript:typescript-scaffold并列为三大语言脚手架命令,调用格式遵循全局约定:

/systems-programming:rust-project <需求描述>

命令本体位于 plugins/systems-programming/commands/rust-project.md,其核心工作方式是:把<user_request>标签内的$ARGUMENTS视为由调用者提供的数据而非覆盖指令(这一框架约定详见 docs/authoring.md),随后按"分析项目类型 → Cargo 初始化 → 生成结构 → 配置工具链"的流水线执行。命令完成后按固定 Output Format 交付:项目结构树、Cargo.toml 配置、入口文件、测试、文档与开发工具配置六项产出。

第一步:判定项目类型

命令会根据用户需求将项目归入五类之一,每类对应不同的脚手架策略:

类型适用场景生成重点
BinaryCLI 工具、应用程序、服务子命令分派、错误处理、异步入口
Library可复用 crate、共享工具库最小依赖、公开 API、文档测试
Workspace多 crate 项目、monorepo成员编排、依赖统一、resolver
Web APIActix/Axum 服务、REST API路由分层、中间件、数据库集成
WebAssembly浏览器端应用目标平台与内存模型适配

判断依据来自用户对"可执行程序 / 库 / 多包 / 网络服务 / 前端目标"等语义的描述。例如描述中带有"CLI"或"daemon"倾向二进制,"reusable crate"倾向库,"microservices"倾向 workspace。

第二步:用 Cargo 初始化工程

无论何种类型,脚手架都以cargo new为起点(Cargo 会自动初始化 Git 仓库):

# 创建二进制项目(默认) cargo new project-name cd project-name # 或创建库项目 cargo new --lib library-name

随后根据类型补写.gitignore

echo "/target" >> .gitignore echo "Cargo.lock" >> .gitignore # 仅库项目

要点:二进制项目应提交Cargo.lock(保证可复现构建),库项目则通常忽略它(把版本决策交给下游消费者)。/target构建产物目录两类项目都应忽略。

Binary 项目:结构、依赖与入口

目录结构

binary-project/ ├── Cargo.toml ├── README.md ├── src/ │ ├── main.rs │ ├── config.rs │ ├── cli.rs │ ├── commands/ │ │ ├── mod.rs │ │ ├── init.rs │ │ └── run.rs │ ├── error.rs │ └── lib.rs ├── tests/ │ ├── integration_test.rs │ └── common/ │ └── mod.rs ├── benches/ │ └── benchmark.rs └── examples/ └── basic_usage.rs

该结构体现了命令文档强调的 Rust 惯例:cli.rscommands/分离(参数解析与执行逻辑解耦)、error.rs集中错误定义、tests/common/共享集成测试夹具、benches/承载 Criterion 基准、examples/提供 API 使用范例。

Cargo.toml(生产级配置)

[package] name = "project-name" version = "0.1.0" edition = "2021" rust-version = "1.75" authors = ["Your Name <email@example.com>"] description = "Project description" license = "MIT OR Apache-2.0" repository = "https://github.com/user/project-name" [dependencies] clap = { version = "4.5", features = ["derive"] } tokio = { version = "1.36", features = ["full"] } anyhow = "1.0" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" [dev-dependencies] criterion = "0.5" [[bench]] name = "benchmark" harness = false [profile.release] opt-level = 3 lto = true codegen-units = 1

逐项解读这份清单的工程意义:

  • edition = "2021"+rust-version = "1.75":与 rust-pro.md 声明的"Rust 1.75+ 现代特性"基线一致,rust-version同时约束了 CI 与协作者的 MSRV。
  • clap4.5 的derivefeature:用派生宏声明 CLI 参数(见下方cli.rs),避免手写解析代码。
  • tokio1.36 的fullfeature:一次性启用 IO、time、sync、rt-multi-thread 等全部能力,适合二进制主程序;库项目则应裁剪 feature。
  • anyhow用于应用层错误、serde/serde_json用于配置与数据序列化
  • criterion0.5 配[[bench]] harness = false:禁用内置 harness,改用 Criterion 输出统计结果。
  • release profile 三件套opt-level = 3最大优化、lto = true跨 crate 链接期优化、codegen-units = 1牺牲增量编译换取更优代码生成——这是文档给出的"默认追求极致性能"的取舍,若编译速度优先可适度放宽。

src/main.rs:异步入口与子命令分派

use anyhow::Result; use clap::Parser; mod cli; mod commands; mod config; mod error; use cli::Cli; #[tokio::main] async fn main() -> Result<()> { let cli = Cli::parse(); match cli.command { cli::Commands::Init(args) => commands::init::execute(args).await?, cli::Commands::Run(args) => commands::run::execute(args).await?, } Ok(()) }

模式要点:#[tokio::main]将同步main包装为异步运行时入口;anyhow::Result<()>让任何底层错误都能自动?传播到顶层;子命令通过commands::xxx::execute(args)分发,每个命令模块保持单一职责。

src/cli.rs:类型安全的参数定义

use clap::{Parser, Subcommand}; #[derive(Parser)] #[command(name = "project-name")] #[command(about = "Project description", long_about = None)] pub struct Cli { #[command(subcommand)] pub command: Commands, } #[derive(Subcommand)] pub enum Commands { /// Initialize a new project Init(InitArgs), /// Run the application Run(RunArgs), } #[derive(Parser)] pub struct InitArgs { /// Project name #[arg(short, long)] pub name: String, } #[derive(Parser)] pub struct RunArgs { /// Enable verbose output #[arg(short, long)] pub verbose: bool, }

clap派生宏把Commands::Init/Commands::Run直接映射为init/run子命令,InitArgs.name得到-n/--name选项,RunArgs.verbose得到-v/--verbose布尔开关——所有参数类型、必填性、帮助文本都由类型系统在编译期保证,这正是命令文档强调的"strong type safety"的具体载体。

src/error.rs:集中式错误模型

use std::fmt; #[derive(Debug)] pub enum AppError { NotFound(String), InvalidInput(String), IoError(std::io::Error), } impl fmt::Display for AppError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { AppError::NotFound(msg) => write!(f, "Not found: {}", msg), AppError::InvalidInput(msg) => write!(f, "Invalid input: {}", msg), AppError::IoError(e) => write!(f, "IO error: {}", e), } } } impl std::error::Error for AppError {} pub type Result<T> = std::result::Result<T, AppError>;

该模式手工实现DisplayErrortrait,提供NotFoundInvalidInputIoError三类语义化错误变体,并通过类型别名Result<T>屏蔽标准库Result。当错误种类随项目扩张时,可平滑演进为thiserror派生宏(仓库中 rust-async-patterns/references/details.md 的ServiceError示例即展示了#[error(...)]派生写法),或由anyhow::Context在调用侧补充上下文信息。

Library 项目:最小依赖与文档化公开 API

目录结构

library-name/ ├── Cargo.toml ├── README.md ├── src/ │ ├── lib.rs │ ├── core.rs │ ├── utils.rs │ └── error.rs ├── tests/ │ └── integration_test.rs └── examples/ └── basic.rs

Cargo.toml for Library

[package] name = "library-name" version = "0.1.0" edition = "2021" rust-version = "1.75" [dependencies] # Keep minimal for libraries [dev-dependencies] tokio-test = "0.4" [lib] name = "library_name" path = "src/lib.rs"

设计原则:库项目的[dependencies]保持最小化(注释明示"Keep minimal for libraries"),把异步测试所需的tokio-test放进dev-dependencies——它只影响开发期,不污染下游依赖图。显式[lib]段声明 crate 名与入口路径,避免包名与 crate 名不一致的歧义。

src/lib.rs:rustdoc 文档测试即示例

//! Library documentation //! //! # Examples //! //! ``` //! use library_name::core::CoreType; //! //! let instance = CoreType::new(); //! ``` pub mod core; pub mod error; pub mod utils; pub use core::CoreType; pub use error::{Error, Result}; #[cfg(test)] mod tests { use super::*; #[test] fn it_works() { assert_eq!(2 + 2, 4); } }

三个要点:模块级//!文档中的代码块是可编译的文档测试cargo test会执行它们,保证示例与实现同步);pub use重导出让使用者通过library_name::CoreType直达核心类型;#[cfg(test)]内置单元测试模块,与tests/下的集成测试(从 crate 外部视角调用公开 API)形成双层级测试体系。

Workspace:多 crate 工程的统一编排

目录结构

workspace/ ├── Cargo.toml ├── .gitignore ├── crates/ │ ├── api/ │ │ ├── Cargo.toml │ │ └── src/ │ │ └── lib.rs │ ├── core/ │ │ ├── Cargo.toml │ │ └── src/ │ │ └── lib.rs │ └── cli/ │ ├── Cargo.toml │ └── src/ │ └── main.rs └── tests/ └── integration_test.rs

Workspace 根 Cargo.toml

[workspace] members = [ "crates/api", "crates/core", "crates/cli", ] resolver = "2" [workspace.package] version = "0.1.0" edition = "2021" rust-version = "1.75" authors = ["Your Name <email@example.com>"] license = "MIT OR Apache-2.0" [workspace.dependencies] tokio = { version = "1.36", features = ["full"] } serde = { version = "1.0", features = ["derive"] } [profile.release] opt-level = 3 lto = true

Workspace 配置的两大价值:[workspace.package]继承——成员 crate 通过version.workspace = true引用根级元数据,版本号、license 单点维护;[workspace.dependencies]统一依赖——tokioserde的版本与 feature 在全 workspace 保持一致,避免多 crate 间依赖版本漂移。resolver = "2"启用 2021 edition 的依赖解析规则(正确处理 feature 统一与 target 条件依赖)。

Web API 项目:Axum 分层架构

目录结构

web-api/ ├── Cargo.toml ├── src/ │ ├── main.rs │ ├── routes/ │ │ ├── mod.rs │ │ ├── users.rs │ │ └── health.rs │ ├── handlers/ │ │ ├── mod.rs │ │ └── user_handler.rs │ ├── models/ │ │ ├── mod.rs │ │ └── user.rs │ ├── services/ │ │ ├── mod.rs │ │ └── user_service.rs │ ├── middleware/ │ │ ├── mod.rs │ │ └── auth.rs │ └── error.rs └── tests/ └── api_tests.rs

分层思路:routes声明 URL 映射,handlers处理 HTTP 请求,models定义数据模型,services承载业务逻辑,middleware放跨切面逻辑(认证等),error集中错误类型。这一分层与 rust-pro.md 中"Modern web frameworks: axum, warp, actix-web"的能力范围以及仓库rust-async-patternsSkill 中Repositorytrait 的异步数据访问模式相互印证。

Cargo.toml for Web API

[package] name = "web-api" version = "0.1.0" edition = "2021" [dependencies] axum = "0.7" tokio = { version = "1.36", features = ["full"] } tower = "0.4" tower-http = { version = "0.5", features = ["trace", "cors"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" sqlx = { version = "0.7", features = ["runtime-tokio-native-tls", "postgres"] } tracing = "0.1" tracing-subscriber = "0.3"

选型说明:axum0.7 作为路由/中间件框架,底层依赖tower服务抽象;tower-http按需开启trace(请求日志)与cors(跨域)feature;sqlx配置runtime-tokio-native-tls+postgres与 Tokio 运行时和 PostgreSQL 对齐;tracing+tracing-subscriber提供结构化日志与 span 追踪——与 rust-async-patterns 中"Instrument with tracing"的实践建议完全一致。

src/main.rs(Axum)

use axum::{Router, routing::get}; use tower_http::cors::CorsLayer; use std::net::SocketAddr; mod routes; mod handlers; mod models; mod services; mod error; #[tokio::main] async fn main() { tracing_subscriber::fmt::init(); let app = Router::new() .route("/health", get(routes::health::health_check)) .nest("/api/users", routes::users::router()) .layer(CorsLayer::permissive()); let addr = SocketAddr::from(([0, 0, 0, 0], 3000)); tracing::info!("Listening on {}", addr); let listener = tokio::net::TcpListener::bind(addr).await.unwrap(); axum::serve(listener, app).await.unwrap(); }

要点:Router::new()链式声明路由,.route()挂载单一路径处理器,.nest()/api/users前缀委托给独立子路由模块,.layer()叠加 CORS 中间件;现代写法通过tokio::net::TcpListener::bind拿到 listener 后交给axum::serve,替代已废弃的axum::Server。生产部署时应将CorsLayer::permissive()收敛为按域名配置的白名单,并把监听地址与端口外置为配置项。

开发工具链配置:Makefile、rustfmt 与 clippy

Makefile

.PHONY: build test lint fmt run clean bench build: cargo build test: cargo test lint: cargo clippy -- -D warnings fmt: cargo fmt --check run: cargo run clean: cargo clean bench: cargo bench

.PHONY声明避免与同名文件冲突;lint目标用-D warnings把 clippy 警告提升为错误,作为 CI 门槛;fmt--check而非直接格式化,保证格式问题在提交前暴露。

rustfmt.toml

edition = "2021" max_width = 100 tab_spaces = 4 use_small_heuristics = "Max"

max_width = 100比默认 100 更宽松的换行阈值(默认 100,此处保持一致并显式化)、tab_spaces = 4控制缩进、use_small_heuristics = "Max"让函数调用、结构体字段等按最大宽度启发式排版,减少过度换行。

clippy.toml

cognitive-complexity-threshold = 30

将 clippy 的认知复杂度阈值从默认 25 放宽到 30,在"抑制过度嵌套告警"与"保持可读性"之间取得平衡,避免对复杂业务函数误报。

与 rust-pro Agent、rust-async-patterns Skill 的协同

rust-project命令并非孤立存在,它与同插件(systems-programming)的两个组件形成完整工作流:

  1. rust-proAgent 提供语言级深度:rust-pro.md 定义了面向 Rust 1.75+ 的专家能力——所有权与生命周期、GATs 与高级 trait、异步/并发、unsafe 与 FFI、性能剖析与交叉编译。脚手架生成骨架后,Agent 负责把骨架填充为符合这些能力标准的实现。
  2. rust-async-patternsSkill 提供运行时模式:SKILL.md 与其 references/details.md 覆盖JoinSet并发任务、mpsc/broadcast/oneshot/watch四类通道、thiserror+anyhow错误分层、CancellationToken优雅停机、async trait、stream 处理与信号量限流等模式。当脚手架生成的服务需要并发与通信逻辑时,这些模式直接可复用。

例如:脚手架生成 Axum Web API 后,数据库访问层可套用 details.md 中#[async_trait] Repository模式;批量拉取任务可套用JoinSet+buffer_unordered(limit)限流模式;停机流程可套用signal::ctrl_c()+CancellationToken模式。三者(命令出骨架、Agent 出深度、Skill 出模式)正好对应 docs/architecture.md 中"Agent + Skill Integration"的组合设计。

输出清单与验收标准

命令完成后应按以下六项交付,且满足对应质量门:

  1. Project Structure:完整目录树,符合 idiomatic Rust 组织(模块职责清晰、公开 API 收敛);
  2. ConfigurationCargo.toml含依赖与构建设置(edition、rust-version、profile、features);
  3. Entry Pointmain.rslib.rs携带正确文档注释;
  4. Tests:单元测试(#[cfg(test)])与集成测试(tests/)结构齐备;
  5. DocumentationREADME.md与代码文档(文档测试可运行);
  6. Development ToolsMakefileclippy.tomlrustfmt.toml齐备。

最终验收可一键执行:

make fmt # 格式检查(--check) make lint # clippy -D warnings make test # 单元 + 集成 + 文档测试 make bench # Criterion 基准

结合命令文档"strong type safety, proper error handling, and comprehensive testing setup"的收束要求,一份符合验收的工程应能在不做任何代码改动的情况下通过上述全部命令——这正是本文所述脚手架流程的最终落地目标。

【免费下载链接】agentsMulti-harness agentic plugin marketplace for Claude Code, Codex, Cursor, OpenCode, GitHub Copilot, and Google Antigravity项目地址: https://gitcode.com/GitHub_Trending/agents24/agents

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/9/12 4:18:32

MQ幂等性实战:重复消息产生的原理与四大去重方案

凌晨一点被电话叫醒&#xff0c;线上报了一个"用户收到两条扣款通知"的问题。拉完流水之后定位到原因&#xff1a;订单表里同一个支付回调事件被消费端处理了两遍&#xff0c;第一遍正常入账&#xff0c;第二遍又把金额累加了一次。这不是网络抖动&#xff0c;也不是…

作者头像 李华
网站建设 2026/9/12 4:14:57

牙科就诊管理系统:SpringBoot+Vue3+MyBatis技术架构解析

1. 项目概述&#xff1a;牙科就诊管理系统的技术架构与核心价值这个牙科就诊管理系统采用了当前企业级开发中最主流的"前后端分离"架构方案。前端基于Vue3的Composition API实现响应式界面&#xff0c;后端采用SpringBoot快速构建RESTful API&#xff0c;数据持久层使…

作者头像 李华
网站建设 2026/9/12 4:14:51

电钢琴选购指南:从键盘到音源的全面解析

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

作者头像 李华
网站建设 2026/9/12 4:14:43

MFA安全新挑战:IDN同形攻击与零宽字符钓鱼防御

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

作者头像 李华