附录A:Rust 语言参考
本附录提供 Rust 编程语言的核心概念、语法规则和功能的简明概述,旨在为开发者提供快速查阅的参考工具。
1. 基本语法规则
1.1 变量声明
- 不可变变量(默认):
let x = 5; // x 是不可变的 - 可变变量:
let mut y = 10; // y 是可变的 y = 20;
1.2 常量
- 定义常量必须指定类型,并且生命周期为整个程序:
const MAX_POINTS: u32 = 100_000;
1.3 数据类型
标量类型:整型、浮点型、布尔型、字符型。
let integer: i32 = -10; let float: f64 = 3.14; let boolean: bool = true; let character: char = 'A';复合类型:元组和数组。
let tuple: (i32, f64, char) = (42, 3.14, 'R'); let array: [i32; 5] = [1, 2, 3, 4, 5];
2. 所有权与借用
2.1 所有权规则
- 每个值有且仅有一个所有者。
- 当所有者离开作用域时,值会被自动释放。
移动:
let s1 = String::from("hello"); let s2 = s1; // s1 被移动,s1 不再可用克隆:
let s1 = String::from("hello"); let s2 = s1.clone(); // 深拷贝,s1 和 s2 都可用
2.2 借用与引用
不可变引用:
let s = String::from("hello"); let len = calculate_length(&s); // 不可变借用可变引用:
let mut s = String::from("hello"); change(&mut s); // 可变借用
3. 控制流
3.1 条件判断
- if 语句:
if x > 0 { println!("Positive"); } else { println!("Negative or Zero"); }
3.2 循环
无限循环:
loop { println!("Running..."); }带条件循环:
while x > 0 { x -= 1; }迭代循环:
for i in 1..=5 { println!("{}", i); }
3.3 模式匹配
- match 语句:
match value { 1 => println!("One"), 2 => println!("Two"), _ => println!("Other"), }
4. 函数与闭包
4.1 函数
- 定义函数:
fn add(a: i32, b: i32) -> i32 { a + b }
4.2 闭包
- 定义闭包:
let add = |a, b| a + b; let result = add(5, 3);
5. 集合与迭代器
5.1 常用集合
向量(Vec):
let mut v = Vec::new(); v.push(1);哈希映射(HashMap):
use std::collections::HashMap; let mut map = HashMap::new(); map.insert("key", "value");
5.2 迭代器
- 创建迭代器:
let nums = vec![1, 2, 3]; for num in nums.iter() { println!("{}", num); }
6. 错误处理
6.1 Result 枚举
- 定义与使用:
let result: Result<i32, &str> = Ok(10); match result { Ok(val) => println!("Value: {}", val), Err(err) => println!("Error: {}", err), }
6.2 Option 枚举
- 定义与使用:
let some_value: Option<i32> = Some(42); if let Some(val) = some_value { println!("Value: {}", val); }
7. 并发与多线程
7.1 创建线程
- 使用 std::thread:
use std::thread; thread::spawn(|| { println!("Hello from another thread!"); });
7.2 消息传递
- 使用 mpsc:
use std::sync::mpsc; let (tx, rx) = mpsc::channel(); tx.send("Hello").unwrap(); println!("{}", rx.recv().unwrap());
8. 常用工具
8.1 Cargo
创建新项目:
cargo new project_name运行项目:
cargo run添加依赖:
编辑Cargo.toml文件:[dependencies] rand = "0.8"
8.2 clippy
安装:
rustup component add clippy运行:
cargo clippy
9. 参考资料
- Rust 官方文档:https://doc.rust-lang.org
- Rust 标准库:https://doc.rust-lang.org/std
- Cargo 指南:https://doc.rust-lang.org/cargo
通过本附录,开发者可以快速定位 Rust 语言核心概念与语法,希望本参考资料能为您的开发旅程提供帮助!
9. 生命周期深入
9.1 显式生命周期标注
生命周期确保引用在有效期内使用,避免悬垂指针。
// 函数签名中的生命周期
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
// 如果返回总是 x,可以收紧约束
fn choose_first<'a, 'b: 'a>(x: &'a str, y: &'b str) -> &'a str {
x // 'b 至少和 'a 一样长
}
9.2 结构体中的生命周期
struct Book<'a> {
title: &'a str,
author: &'a str,
}
impl<'a> Book<'a> {
fn summary(&self) -> String {
format!("{} by {}", self.title, self.author)
}
}
生命周期省略规则(编译器自动推断):
- 每个引用参数都有独立生命周期参数
- 如果只有一个输入生命周期,它赋值给所有输出生命周期
- 如果有
&self或&mut self,其生命周期赋给所有输出
9.3 'static 生命周期
// 'static 表示存活于整个程序运行期间
let s: &'static str = "编译期字符串字面量"; // 存储在只读数据段
// 闭包捕获 'static 的场景
std::thread::spawn(|| {
println!("线程中的 'static 闭包");
});
10. 泛型与 Trait
10.1 泛型函数与结构体
fn largest<T: PartialOrd>(list: &[T]) -> &T {
let mut largest = &list[0];
for item in list {
if item > largest { largest = item; }
}
largest
}
struct Point<T, U> {
x: T,
y: U,
}
impl<T, U> Point<T, U> {
fn x(&self) -> &T { &self.x }
}
// 为特定类型实现
impl Point<i32, i32> {
fn distance_from_origin(&self) -> f64 {
((self.x.pow(2) + self.y.pow(2)) as f64).sqrt()
}
}
10.2 Trait 定义与实现
// 定义 trait
pub trait Drawable {
fn draw(&self);
fn bounds(&self) -> (i32, i32, i32, i32);
fn draw_highlighted(&self) {
println!("Drawing with highlight...");
self.draw();
}
}
pub struct Circle { pub x: i32, pub y: i32, pub r: i32 }
impl Drawable for Circle {
fn draw(&self) {
println!("Circle at ({}, {}) r={}", self.x, self.y, self.r);
}
fn bounds(&self) -> (i32, i32, i32, i32) {
(self.x - self.r, self.y - self.r, self.x + self.r, self.y + self.r)
}
}
10.3 常用标准库 Trait
| Trait | 用途 | 示例 |
|---|---|---|
Display | 格式化输出 {} | println!("{}", obj) |
Debug | 调试输出 {:?} | println!("{:?}", obj) |
Clone | 显式深拷贝 | obj.clone() |
Copy | 按位复制 | 隐式复制,无需 clone() |
PartialEq / Eq | 相等比较 | == / != |
PartialOrd / Ord | 大小比较 | < / > |
Send | 跨线程转移所有权 | 自动实现 |
Sync | 多线程共享引用 | 自动实现 |
11. 智能指针
11.1 Box
enum List {
Cons(i32, Box<List>),
Nil,
}
let list = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
11.2 Rc 与 Arc
use std::rc::Rc;
let data = Rc::new(vec![1, 2, 3]);
let data2 = Rc::clone(&data);
println!("Count: {}", Rc::strong_count(&data)); // 2
use std::sync::Arc;
let shared = Arc::new(String::from("hello"));
let handle = std::thread::spawn({
let shared = Arc::clone(&shared);
move || println!("Thread: {}", shared)
});
11.3 RefCell 与内部可变性
use std::cell::RefCell;
let cell = RefCell::new(5);
{
let mut val = cell.borrow_mut();
*val += 1;
}
println!("{}", cell.borrow()); // 6
12. 常见宏
12.1 声明宏
macro_rules! vec_str {
( $( $x:expr ),* ) => {
{
let mut temp_vec = Vec::new();
$( temp_vec.push($x.to_string()); )*
temp_vec
}
};
}
let v = vec_str!["hello", "world", 2024];
12.2 过程宏(简要)
#[derive(Debug, Clone, PartialEq)]
struct Point { x: i32, y: i32 }
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。