关于 rust-by-example
面向 Rust 开发者的编码技能,提供语言特性的具体写法模式。它将 24 个主题导向示例和参考文件,并说明与相关技能的职责边界。
主要功能
- 01类型转换与流程控制
- 02函数、闭包和模块
- 03泛型与 Trait 模式
- 04错误处理与属性
- 05Unsafe 代码与宏概览
- 06主题参考与技能路由
适用场景
- 01选择 From、Into 或 TryFrom
- 02实现具有合适捕获行为的闭包
- 03组织模块并使用 Trait 对象
- 04通过 ? 和 Result 传播错误
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ full-stack-skills/ rust-skills --skill rust-by-example安装后在 Claude Code 中输入/rust-by-example确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
agents/openai.yamlexamples/golden-by-example/Cargo.lockCargo.tomlexamples/golden-by-example/src/lib.rsreferences/attributes.mdclosures.mdconversions.mderror-handling.mdflow-control.mdgenerics-traits.mdinline-asm.mdmigrating-from-other-languages.mdmodules.mdprocedural-macros-overview.mdunsafe.md详细介绍
Rust by Example — 通过可编译代码片段学习模式
权威来源:Rust by Example —— 官方的示例驱动教程。本技能将其 24 章浓缩为一个路由层,指向针对具体主题的参考文件。
本技能涵盖**“如何编写 X”**模式,并提供具体代码。它不负责架构决策(rust-api-design、rust-workspace)、语言语义(rust-stable)或标准库 API 选择(rust-stdlib)。
能力边界
✅ 优势
- 类型之间的转换 —
From/Into/TryFrom/as/Deref/transmute - 流程控制惯用法 —
if let、while let、match、带标签的loop、? - 函数、方法、闭包(
Fn/FnMut/FnOnce)、捕获模式 - 模块、
use、pub、super/self/crate、基于文件的模块解析 - 泛型 — 函数、结构体、方法、impl 块、
where子句 - Trait — 定义、默认方法、关联类型、Trait 对象、对象安全
- 错误处理 —
?、Result、Option、使用thiserror、anyhow定义自定义错误 - 属性 —
#[derive]、#[cfg]、#[inline]、#[allow]、#[non_exhaustive] - Unsafe — 裸指针、解引用、
unsafe fn/unsafe impl、联合体、ABI - 过程宏 — derive、属性、类函数(高层路由到
rust-macros) - 内联汇编 —
core::arch::asm!(较少用到,但提供支持)
⚠️ 前置要求
- Rust 基础语法 — 参见
rust-stable - 项目结构 — 参见
rust-workspace、rust-module-layout
❌ 不在范围内
- API 设计决策 →
rust-api-design - 工作区 / 模块布局 →
rust-workspace、rust-module-layout - 标准库 API 选择(选择哪种集合、哪种指针) →
rust-stdlib - 异步运行时 →
rust-concurrency - 深入的 unsafe / FFI →
rust-unsafe-ffi - 编写复杂的过程宏 →
rust-macros
数据隐私
本技能不会收集、存储或传输用户数据。
主题索引(每种模式类别对应一个章节)
每个章节都包含一个简短示例;更深入的模式见链接的参考文件。
1. 类型转换
// From / Into (lossless)
impl From<i32> for Wrapped { fn from(v: i32) -> Self { Self(v) } }
let w: Wrapped = 42.into(); // Into comes for free
// TryFrom (fallible)
impl TryFrom<&str> for Email {
type Error = EmailError;
fn try_from(s: &str) -> Result<Self, Self::Error> { /* */ }
}
// as (numeric widening/narrowing — can lose data)
let big: i64 = 1_000_000;
let small: i32 = big as i32; // ❌ silent truncation possible
// Deref (smart-pointer coercion, NOT polymorphism)
let s: String = "hi".to_string();
let s_ref: &str = &s; // Deref<Target=str> kicks in
关于 as、From、TryFrom 的区别,以及各自的适用场景,请参见 references/conversions.md。
2. 流程控制
// if let — single-pattern destructure
if let Some(x) = opt { /* */ }
// while let — loop until None
while let Some(line) = reader.lines().next() { /* */ }
// match with @-binding
match point {
Point { x: 0, y } => println!("on y-axis at {y}"),
Point { x, y: 0 } => println!("on x-axis at {x}"),
p @ Point { x: 10..=20, .. } => println!("in x-band: {p:?}"),
_ => {}
}
// loop with label
'outer: loop {
loop { break 'outer; }
}
关于 match 的易用性、守卫、范围,以及何时优先使用 if let,请参见 references/flow-control.md。
3. 函数和闭包
// Closure captures by ref/move based on use
let v = vec![1, 2, 3];
let print = || println!("{:?}", v); // borrows
let consume = move || { v.into_iter().sum() }; // moves
// Fn / FnMut / FnOnce — how a closure borrows its environment
fn apply(f: impl Fn()) { f() } // can be called multiple times, immutable capture
fn apply_mut(mut f: impl FnMut()) { f() } // mutable capture
fn apply_once(f: impl FnOnce() -> i32) -> i32 { f() } // consumes captured
关于 move 关键字、返回类型推断,以及 Fn/FnMut/FnOnce Trait 约束,请参见 references/closures.md。
4. 模块
// src/lib.rs
pub mod network; // src/network.rs OR src/network/mod.rs
pub use network::Client; // re-export
// src/network.rs
pub struct Client { /* */ }
pub fn connect() { /* */ }
// Using items
use std::collections::HashMap;
use std::io::{self, Read}; // io module + Read trait
use crate::network::Client; // absolute
use super::helper; // parent
use self::inner::Item; // current
关于 pub/pub(crate)/pub(super)、基于文件的模块与 mod.rs 的区别,以及 crate 根重新导出,请参见 references/modules.md。如需深入处理布局,请转到 rust-module-layout。
5. 泛型
// Generic function with bound
fn first<T>(xs: &[T]) -> Option<&T> { xs.first() }
// Generic with where clause
fn sum<T>(xs: &[T]) -> T where T: Default + std::ops::AddAssign + Copy {
let mut acc = T::default();
for x in xs { acc += *x; }
acc
}
// Generic struct
struct Pair<A, B> { a: A, b: B }
impl<A: Clone, B: Clone> Pair<A, B> {
fn swapped(&self) -> Pair<B, A> { Pair { a: self.b.clone(), b: self.a.clone() } }
}
关于单态化成本、何时使用泛型而非 Trait 对象,以及关联类型与泛型的区别,请参见 references/generics-traits.md。
6. Trait
// Definition with default method
pub trait Summary {
fn summarize(&self) -> String;
fn default_summary(&self) -> String { format!("(no summary)") }
}
// Trait object (dynamic dispatch)
fn print_summary(item: &dyn Summary) { println!("{}", item.summarize()); }
// Generic (static dispatch)
fn print_summary_generic<T: Summary>(item: &T) { println!("{}", item.summarize()); }
// Associated type
trait Container { type Item; fn first(&self) -> Option<&Self::Item>; }
对象安全规则:方法签名中不能包含 Self、不能有泛型方法,接收者必须是 sized。参见 references/generics-traits.md。
7. 错误处理
use std::fs;
use std::io;
use std::num::ParseIntError;
// ? propagates with From conversion
fn read_count() -> Result<i32, io::Error> {
let s: String = fs::read_to_string("count.txt")?;
Ok(s.trim().parse().unwrap_or(0)) // or proper error mapping
}
// Custom error with thiserror
#[derive(thiserror::Error, Debug)]
enum Error {
#[error("io: {0}")] Io(#[from] io::Error),
#[error("parse: {0}")] Parse(#[from] ParseIntError),
#[error("not found: {key}")] NotFound { key: String },
}
// Application-layer catch-all with anyhow
fn main() -> anyhow::Result<()> {
let x: i32 = "5".parse()?;
Ok(())
}
关于 ? 与 From 的用法、thiserror 与 anyhow 的区别,以及自定义错误设计,请参见 references/error-handling.md。
8. 属性
#[derive(Debug, Clone, PartialEq)] // generate traits
struct User { id: u32 }
#[cfg(target_os = "linux")] // conditional compilation
fn setup() { /* */ }
#[inline] // hint to inline (rarely matters)
fn fast() {}
#[allow(dead_code)] // suppress warning
struct Unused;
#[non_exhaustive] // allow adding variants
enum Event { Login }
关于完整的属性目录、cfg 表达式,以及 #[inline] 何时确实有用,请参见 references/attributes.md。
9. Unsafe
// Raw pointer dereference
let x = 42;
let ptr: *const i32 = &x;
let val = unsafe { *ptr };
// Splitting a slice (needs unsafe for non-overlapping aliasing)
let mut v = vec![1, 2, 3, 4];
let (left, right) = v.split_at_mut(2); // safe wrapper
// Calling C ABI
extern "C" { fn abs(input: i32) -> i32; }
let a = unsafe { abs(-5) };
// Union (unsafe to read)
#[repr(C)]
union Value { i: i32, f: f32 }
关于安全契约、四种 unsafe 超能力,以及何时应使用它,请参见 references/unsafe.md。如需深入了解 FFI,请转到 rust-unsafe-ffi。
10. 过程宏(仅概述)
// Derive (most common)
#[derive(Debug, Clone, serde::Serialize)]
struct Config { /* */ }
// Attribute macro
#[tokio::main]
async fn main() { /* */ }
// Function-like macro
let html = html! { <div>Hello</div> };
编写过程宏较为复杂——请转到 rust-macros。本技能仅介绍如何使用它们。
关于三种过程宏及其各自的适用场景,请参见 references/procedural-macros-overview.md。
11. 内联汇编
#[cfg(target_arch = "x86_64")]
fn halt() {
unsafe { std::arch::asm!("hlt", options(nostack)); }
}
关于 asm! 语法、寄存器冲突,以及何时使用它(仅限内核 / 嵌入式场景),请参见 references/inline-asm.md。
工作流
- 识别问题 — “如何编写 X” → 使用此技能;“使用哪种类型” →
rust-stdlib;“如何设计架构” →rust-api-design。 - 找到对应参考资料 — 上文第 1–11 节,或
references/中的文件。 - 阅读最小示例 — 参考其模式,并根据你的代码进行调整。
- 验证 —
cargo check、cargo clippy。 - 移交 — 更深入的问题转交给专门技能。
快速决策
| 问题 | 位置 |
|---|---|
| 如何转换类型? | references/conversions.md |
如何编写 if let/match? | references/flow-control.md |
| 闭包如何捕获变量? | references/closures.md |
mod/use/pub 如何工作? | references/modules.md |
| 泛型 fn/struct/impl? | references/generics-traits.md |
| Trait 对象与泛型该选哪个? | references/generics-traits.md |
| 如何传播错误? | references/error-handling.md |
有哪些 #[derive]/#[cfg]? | references/attributes.md |
什么时候可以使用 unsafe? | references/unsafe.md |
| 如何编写过程宏? | rust-macros skill |
asm! 是什么样的? | references/inline-asm.md |
从其他语言迁移
| 在……中的模式 | ……在 Rust 中变为 |
|---|---|
| Java interface + impl | Rust trait + impl 块 |
Java 泛型 <T extends Foo> | Rust <T: Foo> 或 where T: Foo |
Java Optional<T> | Rust Option<T> |
| Java try/catch | Rust ? + Result |
Python with | Rust Drop(RAII) |
| Python 装饰器 | Rust 属性宏 |
Go goroutine | Rust thread::spawn 或 async 任务 |
Go interface{} | Rust dyn Trait 或泛型 |
| C++ RAII 析构函数 | Rust Drop trait |
C++ reinterpret_cast | Rust unsafe { transmute }(避免使用) |
更多对应关系,请参阅 references/migrating-from-other-languages.md。
资源
- 类型转换
- 流程控制
- 闭包
- 模块
- 泛型和 Trait
- 错误处理
- 属性
- Unsafe
- 过程宏概览
- 内联汇编
- 从其他语言迁移
examples/golden-by-example/:一个涵盖各类模式的 crate