关于 coding-rust
coding-rust 是面向 Rust 开发者的编程技能,涵盖所有权、异步编程、错误处理和 Cargo 工作区,适用于系统代码与多 crate 项目。
主要功能
- 01所有权与生命周期管理
- 02Trait 与多态实现
- 03Tokio 异步任务
- 04anyhow 与 thiserror 错误处理
- 05Cargo 工作区组织
- 06受控使用 unsafe
适用场景
- 01编写借用安全的 Rust 代码
- 02使用 Tokio 构建异步程序
- 03组织多 crate 项目
- 04为 CLI 程序设计错误处理
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ alphaonedev/ openclaw-graph --skill coding-rust安装后在 Claude Code 中输入/coding-rust确认已加载。
详细介绍
coding-rust
用途
此技能提供高级 Rust 编程方面的专业知识,重点介绍核心语言特性和生态系统工具,以构建高效、安全的系统代码。
适用场景
- 使用所有权、借用或生命周期实现内存安全代码,以避免数据竞争等常见错误。
- 需要使用 Tokio 进行异步编程、通过 anyhow/thiserror 处理错误,或使用 Cargo 工作区管理多 crate 项目的场景。
- 涉及在性能关键部分使用 unsafe 代码,或通过 trait 定义自定义行为的场景。
核心能力
- 管理 Rust 的所有权模型:使用引用(&T)和生命周期('a)借用数据,而不转移所有权。
- 实现 trait:定义并使用 trait 对象实现多态,例如
trait Debug { fn fmt(&self); }。 - 使用 Tokio 处理异步任务:通过
tokio::main和 future 运行异步任务。 - 错误管理:使用 anyhow 简单包装错误,使用 thiserror 定义自定义错误类型。
- Cargo 工作区:使用
Cargo.toml工作区组织多包项目,以共享依赖项。 - unsafe 操作:使用 unsafe 块处理原始指针或 FFI,并确保安全不变量得到维护。
使用模式
- 处理所有权和借用时,始终优先借用而非克隆:使用
&mut T表示可变引用,并确保生命周期匹配,例如在fn borrow lifetimes<'a>(x: &'a i32) -> &'a i32等函数中。 - 执行异步任务时,启动 Tokio 运行时:使用
tokio::spawn并发运行 future,然后在异步 main 函数中等待结果。 - 定义 trait 以便扩展:创建一个 trait 并为结构体实现它,例如
impl MyTrait for MyStruct { fn method() { ... } }。 - 设置 Cargo 工作区:在根目录的
Cargo.toml中添加[workspace]部分,并设置members = ["crate1", "crate2"],然后使用cargo build --workspace构建。 - 使用 anyhow 处理错误:通过
anyhow::Result包装错误,并使用?运算符传播错误。 - 尽量少用 unsafe:将 unsafe 代码放在
unsafe { *ptr = value; }这样的块中,并用注释说明理由。
常用命令/API
- Cargo 命令:使用
cargo build --release构建优化后的二进制文件;使用cargo test --workspace测试所有 crate;通过cargo add tokio --features full添加依赖项。 - Tokio API:使用
#[tokio::main] async fn main() { tokio::spawn(async { ... }); }启动异步运行时;使用 channel 进行异步通信,例如let (tx, rx) = tokio::sync::mpsc::channel(10);。 - Anyhow/thiserror:使用
#[derive(thiserror::Error)] enum MyError { ... }定义自定义错误;在函数中按如下方式处理:fn example() -> anyhow::Result<()> { ... }。 - 所有权辅助工具:使用
std::mem::drop等标准库函数显式丢弃值,或使用std::borrow::Cow处理自有或复制的数据。 - 配置格式:编辑
Cargo.toml中的项目设置,例如[dependencies] tokio = { version = "1.0", features = ["full"] };使用环境变量存储密钥,例如调试时设置RUST_BACKTRACE=1。
集成说明
- 与其他工具集成:使用
$RUSTUP_TOOLCHAIN环境变量切换 Rust 版本,例如设置不稳定特性时运行export RUSTUP_TOOLCHAIN=nightly。 - 在外部集成中使用 API 密钥(例如从 Rust 调用外部服务时),设置
$MY_API_KEY等环境变量,并通过std::env::var("MY_API_KEY").unwrap()读取。 - 与构建工具配合:在 CI/CD 中,于构建前运行
cargo fmt格式化代码,并运行cargo clippy检查代码。 - 嵌入项目:在
Cargo.toml中添加 Tokio 作为依赖项,然后在代码中通过use tokio::runtime::Runtime; let rt = Runtime::new().unwrap(); rt.block_on(async { ... });导入并使用。 - 处理工作区中的跨 crate 依赖:通过路径引用 crate,例如在
Cargo.toml中使用path = "../sibling_crate"。
错误处理
- 使用 anyhow 快速传播错误:从函数返回
anyhow::Result<T>,并使用?处理错误,例如:fn read_file() -> anyhow::Result<String> { std::fs::read_to_string("file.txt").context("Failed to read") }。 - 使用 thiserror 定义自定义错误:派生错误,例如
#[derive(thiserror::Error, Debug)] enum AppError { #[error("IO error: {0}")] Io(#[from] std::io::Error), },并使用 match 语句处理。 - 在异步上下文中,使用 Tokio 的错误类型:等待 Future,并使用
.await.map_err(|e| anyhow::Error::from(e))处理错误。 - 始终检查不安全代码中是否可能发生 panic:在不安全代码块周围使用
std::panic::catch_unwind,以防止崩溃。
具体用法示例
- 使用 Tokio 构建异步 HTTP 服务:在
Cargo.toml中添加 Tokio,然后编写:use tokio::net::TcpListener; #[tokio::main] async fn main() -> anyhow::Result<()> { let listener = TcpListener::bind("127.0.0.1:8080").await?; loop { let (socket, _) = listener.accept().await?; tokio::spawn(handle_connection(socket)); } }。 - 在 CLI 工具中处理错误:定义错误并使用 anyhow:在
Cargo.toml中添加anyhow = "1.0"和thiserror = "1.0",然后实现:use thiserror::Error; #[derive(Error, Debug)] enum Error { #[error("Parse error")] Parse, } fn main() -> anyhow::Result<()> { let input = std::env::args().nth(1)?; if input.parse::<u32>().is_err() { Err(Error::Parse)?; } Ok(()) }。
图关系
- 相关项:coding(集群),因为它共享“coding”等标签,并专注于编程技能。
- 关联方式:标签 ["rust", "systems"],可能会关联到其他 Rust 或系统编程技能。
- 依赖项:可与“coding”集群中的技能集成,例如通用编程工具,以提供更广泛的生态系统支持。
评论
支持 Markdown