Rust 入门基础:安全、并发与高性能的系统编程语言

🎬 博主名称个人主页
🔥 个人专栏 : 《C语言》《C语言刷题(初阶)》

⛺️相信总有一天我写的代码也能改变世界!


文章目录

    • 引言
    • [第一章:Rust 环境搭建与工具链](#第一章:Rust 环境搭建与工具链)
      • [1.1 安装 Rust](#1.1 安装 Rust)
      • [1.2 Cargo:Rust 的构建系统和包管理器](#1.2 Cargo:Rust 的构建系统和包管理器)
      • [1.3 开发环境配置](#1.3 开发环境配置)
    • [第二章:Rust 基础语法与核心概念](#第二章:Rust 基础语法与核心概念)
      • [2.1 变量与可变性](#2.1 变量与可变性)
      • [2.2 数据类型系统](#2.2 数据类型系统)
      • [2.3 函数与控制流](#2.3 函数与控制流)
    • [第三章:Rust 核心特性 - 所有权系统](#第三章:Rust 核心特性 - 所有权系统)
      • [3.1 所有权基本规则](#3.1 所有权基本规则)
      • [3.2 移动(Move)语义](#3.2 移动(Move)语义)
      • [3.3 借用与引用](#3.3 借用与引用)
      • [3.4 切片(Slice)类型](#3.4 切片(Slice)类型)
    • 第四章:结构体与枚举
      • [4.1 结构体定义与使用](#4.1 结构体定义与使用)
      • [4.2 方法语法](#4.2 方法语法)
      • [4.3 枚举与模式匹配](#4.3 枚举与模式匹配)
      • [4.4 Option 和 Result 枚举](#4.4 Option 和 Result 枚举)
      • [4.5 强大的模式匹配](#4.5 强大的模式匹配)
    • 第五章:模块系统与包管理
      • [5.1 模块系统基础](#5.1 模块系统基础)
      • [5.2 可见性控制](#5.2 可见性控制)
      • [5.3 use 声明与重导出](#5.3 use 声明与重导出)
    • 第六章:错误处理
      • [6.1 不可恢复错误与 panic!](#6.1 不可恢复错误与 panic!)
      • [6.2 Result 类型与错误处理](#6.2 Result 类型与错误处理)
      • [6.3 自定义错误类型](#6.3 自定义错误类型)
    • 第七章:泛型、特质与生命周期
      • [7.1 泛型](#7.1 泛型)
      • [7.2 特质(Trait)](#7.2 特质(Trait))
      • [7.3 生命周期](#7.3 生命周期)
    • 第八章:集合类型
      • [8.1 Vector](#8.1 Vector)
      • [8.2 String](#8.2 String)
      • [8.3 HashMap](#8.3 HashMap)
    • 第九章:智能指针
      • [9.1 Box<T> - 在堆上分配数据](#9.1 Box<T> - 在堆上分配数据)
      • [9.2 Deref 和 Drop 特质](#9.2 Deref 和 Drop 特质)
      • [9.3 Rc<T> - 引用计数智能指针](#9.3 Rc<T> - 引用计数智能指针)
      • [9.4 RefCell<T> 和内部可变性模式](#9.4 RefCell<T> 和内部可变性模式)
      • [9.5 引用循环与内存泄漏](#9.5 引用循环与内存泄漏)
    • 第十章:并发编程
      • [10.1 使用线程](#10.1 使用线程)
      • [10.2 消息传递并发](#10.2 消息传递并发)
      • [10.3 共享状态并发](#10.3 共享状态并发)
      • [10.4 Sync 和 Send 特质](#10.4 Sync 和 Send 特质)
    • 第十一章:高级特性
      • [11.1 不安全 Rust](#11.1 不安全 Rust)
      • [11.2 高级特质](#11.2 高级特质)
      • [11.3 高级类型](#11.3 高级类型)
      • [11.4 高级函数与闭包](#11.4 高级函数与闭包)
    • 第十二章:宏
      • [12.1 声明宏](#12.1 声明宏)
      • [12.2 过程宏](#12.2 过程宏)
    • [第十三章:实战项目 - 构建简单的 Web 服务器](#第十三章:实战项目 - 构建简单的 Web 服务器)
      • [13.1 项目结构](#13.1 项目结构)
      • [13.2 线程池实现](#13.2 线程池实现)
      • [13.3 HTTP 模块](#13.3 HTTP 模块)
      • [13.4 主程序](#13.4 主程序)
    • 第十四章:测试与文档
      • [14.1 单元测试](#14.1 单元测试)
      • [14.2 集成测试](#14.2 集成测试)
      • [14.3 文档测试](#14.3 文档测试)
    • 第十五章:性能优化与最佳实践
      • [15.1 性能优化技巧](#15.1 性能优化技巧)
      • [15.2 内存管理最佳实践](#15.2 内存管理最佳实践)
    • 结语

引言

在当今的软件开发领域,我们面临着前所未有的挑战:既要保证程序的性能和效率,又要确保内存安全和并发安全。传统的系统级语言如 C 和 C++ 提供了强大的性能,但在安全方面存在显著缺陷;而现代高级语言在安全性上有所改进,却往往以性能损失为代价。

Rust 应运而生,它通过独特的所有权系统和类型系统,在编译时就能检测出内存管理错误和数据竞争问题,实现了"零成本抽象"的理念。自 2016 年起,Rust 连续多年在 Stack Overflow 开发者调查中被评为"最受喜爱的编程语言",这充分证明了其在开发者社区中的影响力。

本文将深入探讨 Rust 的核心概念,通过丰富的实践示例,帮助您全面掌握这门现代系统编程语言。

第一章:Rust 环境搭建与工具链

1.1 安装 Rust

Rust 的官方工具链 rustup 提供了跨平台的安装和管理方案:

bash 复制代码
# Linux 或 macOS
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

# Windows
# 下载并运行 rustup-init.exe

# 安装后验证
rustc --version
cargo --version

1.2 Cargo:Rust 的构建系统和包管理器

Cargo 是 Rust 生态系统的核心工具,它集成了依赖管理、构建、测试、文档生成等多项功能。

Cargo.toml 文件示例:

toml 复制代码
[package]
name = "my_project"
version = "0.1.0"
edition = "2021"

[dependencies]
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1.0", features = ["full"] }

[dev-dependencies]
assert_eq = "0.1.0"

常用 Cargo 命令:

bash 复制代码
cargo new project_name      # 创建新项目
cargo build                # 编译项目
cargo run                  # 编译并运行
cargo test                 # 运行测试
cargo check               # 快速检查编译错误
cargo doc                 # 生成文档
cargo fmt                 # 代码格式化
cargo clippy              # 静态分析

1.3 开发环境配置

推荐使用 VS Code 配合以下扩展:

  • rust-analyzer:提供代码补全、类型提示等智能功能
  • CodeLLDB:调试支持
  • Crates:依赖管理辅助

第二章:Rust 基础语法与核心概念

2.1 变量与可变性

Rust 的变量默认是不可变的,这有助于编写安全的并发代码:

rust 复制代码
fn main() {
    // 不可变变量
    let x = 5;
    // x = 6;  // 编译错误!
    
    // 可变变量
    let mut y = 5;
    y = 6;    // 正确
    
    // 变量遮蔽 (shadowing)
    let z = 5;
    let z = z + 1;        // 创建新变量
    let z = "hello";      // 甚至可以改变类型
    
    // 常量
    const MAX_POINTS: u32 = 100_000;
}

2.2 数据类型系统

Rust 是静态强类型语言,拥有丰富的数据类型:

标量类型:

rust 复制代码
fn scalar_types() {
    // 整数类型
    let i8_val: i8 = -128;
    let u8_val: u8 = 255;
    let isize_val: isize = -100;  // 平台相关
    let usize_val: usize = 100;   // 平台相关
    
    // 浮点类型
    let f32_val: f32 = 3.14;
    let f64_val: f64 = 2.71828;
    
    // 布尔类型
    let t = true;
    let f: bool = false;
    
    // 字符类型 (Unicode 标量值)
    let c = 'z';
    let heart_eyed_cat = '😻';
}

复合类型:

rust 复制代码
fn compound_types() {
    // 元组
    let tup: (i32, f64, u8) = (500, 6.4, 1);
    let (x, y, z) = tup;  // 解构
    let five_hundred = tup.0;
    
    // 数组
    let a = [1, 2, 3, 4, 5];
    let months = ["January", "February", "March"];
    let first = a[0];
    let second = a[1];
    
    // 数组类型注解
    let a: [i32; 5] = [1, 2, 3, 4, 5];
    
    // 初始化相同值的数组
    let a = [3; 5];  // 等同于 [3, 3, 3, 3, 3]
}

2.3 函数与控制流

函数定义:

rust 复制代码
// 带有返回值的函数
fn add(x: i32, y: i32) -> i32 {
    x + y  // 注意:没有分号,这是表达式
}

// 提前返回
fn early_return(x: i32) -> i32 {
    if x < 0 {
        return -1;
    }
    x * 2
}

// 函数指针类型
fn apply_twice(f: fn(i32) -> i32, x: i32) -> i32 {
    f(f(x))
}

控制流:

rust 复制代码
fn control_flow() {
    let number = 6;
    
    // if 表达式
    let result = if number % 2 == 0 {
        "even"
    } else {
        "odd"
    };
    
    // 循环
    let mut counter = 0;
    let result = loop {
        counter += 1;
        if counter == 10 {
            break counter * 2;
        }
    };
    
    // while 循环
    while counter > 0 {
        println!("{}!", counter);
        counter -= 1;
    }
    
    // for 循环遍历集合
    let a = [10, 20, 30, 40, 50];
    for element in a.iter() {
        println!("the value is: {}", element);
    }
    
    // 范围迭代
    for number in 1..4 {
        println!("{}!", number);
    }
}

第三章:Rust 核心特性 - 所有权系统

3.1 所有权基本规则

Rust 的所有权系统基于三个核心规则:

  1. Rust 中的每一个值都有一个被称为其所有者的变量
  2. 值在任一时刻有且只有一个所有者
  3. 当所有者离开作用域,这个值将被丢弃

作用域示例:

rust 复制代码
fn ownership_basics() {
    {                      // s 在这里无效,它尚未声明
        let s = "hello";   // s 从这里开始有效
        
        // 使用 s
        println!("{}", s);
    }                      // 此作用域已结束,s 不再有效
}

3.2 移动(Move)语义

rust 复制代码
fn move_semantics() {
    // 简单类型在栈上复制
    let x = 5;
    let y = x;  // 复制
    
    // String 类型在堆上分配
    let s1 = String::from("hello");
    let s2 = s1;  // s1 被移动到 s2,s1 不再有效
    
    // println!("{}", s1);  // 编译错误!
    
    // 克隆(深拷贝)
    let s3 = String::from("hello");
    let s4 = s3.clone();  // 两个独立的所有权
    println!("s3 = {}, s4 = {}", s3, s4);
}

3.3 借用与引用

不可变引用:

rust 复制代码
fn borrowing() {
    let s1 = String::from("hello");
    
    // 不可变引用
    let len = calculate_length(&s1);
    println!("The length of '{}' is {}.", s1, len);
    
    // 多个不可变引用是允许的
    let r1 = &s1;
    let r2 = &s1;
    println!("{} and {}", r1, r2);
}

fn calculate_length(s: &String) -> usize {
    s.len()
}

可变引用:

rust 复制代码
fn mutable_borrowing() {
    let mut s = String::from("hello");
    
    // 可变引用
    change(&mut s);
    println!("{}", s);
    
    // 在特定作用域中的特定数据只能有一个可变引用
    let r1 = &mut s;
    // let r2 = &mut s;  // 编译错误!
    
    // 但可以这样使用
    {
        let r2 = &mut s;
        r2.push_str(" world");
    } // r2 离开作用域
    
    let r3 = &mut s;  // 现在可以创建新的可变引用
}

fn change(some_string: &mut String) {
    some_string.push_str(", world");
}

3.4 切片(Slice)类型

切片是对集合中一段连续元素的引用:

rust 复制代码
fn slice_demo() {
    let s = String::from("hello world");
    
    // 字符串切片
    let hello = &s[0..5];
    let world = &s[6..11];
    
    // 更好的写法
    let first_word = first_word(&s);
    println!("First word: {}", first_word);
    
    // 数组切片
    let a = [1, 2, 3, 4, 5];
    let slice = &a[1..3];  // 类型为 &[i32]
}

fn first_word(s: &str) -> &str {
    let bytes = s.as_bytes();
    
    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return &s[0..i];
        }
    }
    
    &s[..]
}

第四章:结构体与枚举

4.1 结构体定义与使用

rust 复制代码
// 定义结构体
struct User {
    username: String,
    email: String,
    sign_in_count: u64,
    active: bool,
}

// 元组结构体
struct Color(i32, i32, i32);
struct Point(i32, i32, i32);

// 单元结构体
struct AlwaysEqual;

fn struct_demo() {
    // 创建结构体实例
    let user1 = User {
        email: String::from("someone@example.com"),
        username: String::from("someusername123"),
        active: true,
        sign_in_count: 1,
    };
    
    // 使用结构体更新语法
    let user2 = User {
        email: String::from("another@example.com"),
        username: String::from("anotherusername567"),
        ..user1
    };
    
    // 元组结构体
    let black = Color(0, 0, 0);
    let origin = Point(0, 0, 0);
}

4.2 方法语法

rust 复制代码
#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

// 实现结构体方法
impl Rectangle {
    // 关联函数(类似静态方法)
    fn square(size: u32) -> Rectangle {
        Rectangle {
            width: size,
            height: size,
        }
    }
    
    // 方法 - 第一个参数总是 self
    fn area(&self) -> u32 {
        self.width * self.height
    }
    
    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width > other.width && self.height > other.height
    }
    
    // 可变方法
    fn double_size(&mut self) {
        self.width *= 2;
        self.height *= 2;
    }
}

fn method_demo() {
    let rect1 = Rectangle {
        width: 30,
        height: 50,
    };
    
    let mut rect2 = Rectangle::square(10);
    
    println!("Area: {}", rect1.area());
    println!("Can hold: {}", rect1.can_hold(&rect2));
    
    rect2.double_size();
    println!("Doubled: {:?}", rect2);
}

4.3 枚举与模式匹配

rust 复制代码
// 基本枚举
enum IpAddrKind {
    V4,
    V6,
}

// 带数据的枚举
enum IpAddr {
    V4(u8, u8, u8, u8),
    V6(String),
}

// 复杂枚举
enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

// 枚举方法
impl Message {
    fn call(&self) {
        // 方法实现
    }
}

fn enum_demo() {
    let four = IpAddrKind::V4;
    let six = IpAddrKind::V6;
    
    let home = IpAddr::V4(127, 0, 0, 1);
    let loopback = IpAddr::V6(String::from("::1"));
    
    let msg = Message::Write(String::from("hello"));
    msg.call();
}

4.4 Option 和 Result 枚举

rust 复制代码
fn option_result_demo() {
    // Option<T> 用于处理可能不存在的值
    let some_number = Some(5);
    let some_string = Some("a string");
    let absent_number: Option<i32> = None;
    
    // Result<T, E> 用于错误处理
    let success: Result<i32, String> = Ok(42);
    let failure: Result<i32, String> = Err(String::from("Something went wrong"));
    
    // 模式匹配处理 Option 和 Result
    match some_number {
        Some(value) => println!("Got value: {}", value),
        None => println!("Got nothing"),
    }
    
    match success {
        Ok(value) => println!("Success: {}", value),
        Err(error) => println!("Error: {}", error),
    }
}

4.5 强大的模式匹配

rust 复制代码
fn pattern_matching() {
    let some_value = Some(7);
    
    // match 表达式必须覆盖所有可能情况
    match some_value {
        Some(3) => println!("three"),
        Some(7) => println!("seven"),
        Some(other) => println!("Other: {}", other),
        None => println!("Nothing"),
    }
    
    // if let 语法糖
    let config_max = Some(3u8);
    if let Some(max) = config_max {
        println!("The maximum is configured to be {}", max);
    }
    
    // while let
    let mut stack = Vec::new();
    stack.push(1);
    stack.push(2);
    stack.push(3);
    
    while let Some(top) = stack.pop() {
        println!("{}", top);
    }
    
    // 模式在函数参数中
    let point = (3, 5);
    print_coordinates(&point);
}

fn print_coordinates(&(x, y): &(i32, i32)) {
    println!("Current location: ({}, {})", x, y);
}

第五章:模块系统与包管理

5.1 模块系统基础

复制代码
my_project/
├── Cargo.toml
└── src/
    ├── main.rs
    ├── lib.rs
    └── network/
        ├── mod.rs
        └── server.rs

模块定义示例:

rust 复制代码
// src/lib.rs
mod network;
mod client;

pub use client::Client;

pub fn connect() {
    println!("Connecting...");
}

// src/network/mod.rs
pub mod server;

pub fn connect() {
    println!("Network connecting...");
}

// src/network/server.rs
pub fn connect() {
    println!("Server connecting...");
}

// src/client.rs
pub struct Client {
    pub name: String,
    pub id: u32,
}

impl Client {
    pub fn new(name: String, id: u32) -> Self {
        Client { name, id }
    }
}

5.2 可见性控制

rust 复制代码
mod my_mod {
    // 默认私有
    fn private_function() {
        println!("called `my_mod::private_function()`");
    }
    
    // 公有函数
    pub fn function() {
        println!("called `my_mod::function()`");
    }
    
    // 在同一模块中,可以访问私有项
    pub fn indirect_access() {
        print!("called `my_mod::indirect_access()`, that\n> ");
        private_function();
    }
    
    // 嵌套模块
    pub mod nested {
        pub fn function() {
            println!("called `my_mod::nested::function()`");
        }
        
        // 使用 pub(super) 限制可见性到父模块
        pub(super) fn super_function() {
            println!("called `my_mod::nested::super_function()`");
        }
    }
    
    // 结构体的可见性
    pub struct WhiteBox<T> {
        pub contents: T,
    }
    
    // 枚举的所有变体都是公有的
    pub enum PublicEnum {
        A,
        B,
    }
}

5.3 use 声明与重导出

rust 复制代码
// 使用 use 引入路径
use std::collections::HashMap;
use std::io::{self, Write};
use std::fmt::Result;
use std::io::Result as IoResult;

// 重导出
pub use std::collections::HashMap as Map;

fn use_declarations() {
    let mut map = HashMap::new();
    map.insert(1, 2);
    
    let mut other_map = Map::new();
    other_map.insert(3, 4);
}

// 使用外部 crate
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct Point {
    x: i32,
    y: i32,
}

第六章:错误处理

6.1 不可恢复错误与 panic!

rust 复制代码
fn panic_demo() {
    // 直接调用 panic!
    // panic!("crash and burn");
    
    // 通过索引越界引起 panic
    let v = vec![1, 2, 3];
    // v[99];  // 这会导致 panic!
}

6.2 Result 类型与错误处理

rust 复制代码
use std::fs::File;
use std::io::{self, Read};

// 基本的错误处理
fn basic_error_handling() -> Result<String, io::Error> {
    let f = File::open("hello.txt");
    
    let mut f = match f {
        Ok(file) => file,
        Err(e) => return Err(e),
    };
    
    let mut s = String::new();
    
    match f.read_to_string(&mut s) {
        Ok(_) => Ok(s),
        Err(e) => Err(e),
    }
}

// 使用 ? 运算符简化错误处理
fn simplified_error_handling() -> Result<String, io::Error> {
    let mut f = File::open("hello.txt")?;
    let mut s = String::new();
    f.read_to_string(&mut s)?;
    Ok(s)
}

// 更简洁的写法
fn even_simpler() -> Result<String, io::Error> {
    let mut s = String::new();
    File::open("hello.txt")?.read_to_string(&mut s)?;
    Ok(s)
}

// 链式调用
fn read_username_from_file() -> Result<String, io::Error> {
    std::fs::read_to_string("hello.txt")
}

6.3 自定义错误类型

rust 复制代码
use std::fmt;
use std::error::Error;

#[derive(Debug)]
enum MyError {
    Io(std::io::Error),
    Parse(std::num::ParseIntError),
    Custom(String),
}

impl fmt::Display for MyError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            MyError::Io(err) => write!(f, "IO error: {}", err),
            MyError::Parse(err) => write!(f, "Parse error: {}", err),
            MyError::Custom(msg) => write!(f, "Custom error: {}", msg),
        }
    }
}

impl Error for MyError {}

impl From<std::io::Error> for MyError {
    fn from(err: std::io::Error) -> MyError {
        MyError::Io(err)
    }
}

impl From<std::num::ParseIntError> for MyError {
    fn from(err: std::num::ParseIntError) -> MyError {
        MyError::Parse(err)
    }
}

fn use_custom_error() -> Result<(), MyError> {
    let content = std::fs::read_to_string("config.txt")?;
    let number: i32 = content.trim().parse()?;
    
    if number < 0 {
        return Err(MyError::Custom("Number must be positive".to_string()));
    }
    
    Ok(())
}

第七章:泛型、特质与生命周期

7.1 泛型

rust 复制代码
// 泛型函数
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> {
    x: T,
    y: T,
}

impl<T> Point<T> {
    fn x(&self) -> &T {
        &self.x
    }
}

// 为特定类型实现方法
impl Point<f32> {
    fn distance_from_origin(&self) -> f32 {
        (self.x.powi(2) + self.y.powi(2)).sqrt()
    }
}

// 多个泛型参数
struct MultiPoint<T, U> {
    x: T,
    y: U,
}

impl<T, U> MultiPoint<T, U> {
    fn mixup<V, W>(self, other: MultiPoint<V, W>) -> MultiPoint<T, W> {
        MultiPoint {
            x: self.x,
            y: other.y,
        }
    }
}

7.2 特质(Trait)

rust 复制代码
// 特质定义
pub trait Summary {
    fn summarize(&self) -> String;
    
    // 默认实现
    fn summarize_author(&self) -> String {
        String::from("(Unknown author)")
    }
    
    fn default_summary(&self) -> String {
        format!("(Read more from {}...)", self.summarize_author())
    }
}

// 为类型实现特质
struct NewsArticle {
    pub headline: String,
    pub location: String,
    pub author: String,
    pub content: String,
}

impl Summary for NewsArticle {
    fn summarize(&self) -> String {
        format!("{}, by {} ({})", self.headline, self.author, self.location)
    }
    
    fn summarize_author(&self) -> String {
        self.author.clone()
    }
}

struct Tweet {
    pub username: String,
    pub content: String,
    pub reply: bool,
    pub retweet: bool,
}

impl Summary for Tweet {
    fn summarize(&self) -> String {
        format!("{}: {}", self.username, self.content)
    }
}

// 特质作为参数
fn notify(item: &impl Summary) {
    println!("Breaking news! {}", item.summarize());
}

// 特质边界语法
fn notify_bound<T: Summary>(item: &T) {
    println!("Breaking news! {}", item.summarize());
}

// 多个特质边界
fn notify_multiple(item: &(impl Summary + Display)) {
    // ...
}

// where 子句
fn some_function<T, U>(t: &T, u: &U) -> i32
where
    T: Display + Clone,
    U: Clone + Debug,
{
    // ...
}

// 返回实现特质的类型
fn returns_summarizable() -> impl Summary {
    Tweet {
        username: String::from("horse_ebooks"),
        content: String::from("of course, as you probably already know, people"),
        reply: false,
        retweet: false,
    }
}

7.3 生命周期

rust 复制代码
// 生命周期注解
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}

// 结构体中的生命周期
struct ImportantExcerpt<'a> {
    part: &'a str,
}

impl<'a> ImportantExcerpt<'a> {
    fn level(&self) -> i32 {
        3
    }
    
    fn announce_and_return_part(&self, announcement: &str) -> &str {
        println!("Attention please: {}", announcement);
        self.part
    }
}

// 静态生命周期
fn static_lifetime() -> &'static str {
    "I have a static lifetime."
}

// 生命周期省略规则示例
fn first_word(s: &str) -> &str {  // 编译器会自动添加生命周期
    let bytes = s.as_bytes();
    
    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return &s[0..i];
        }
    }
    
    &s[..]
}

fn lifetime_demo() {
    let string1 = String::from("long string is long");
    let result;
    {
        let string2 = String::from("xyz");
        result = longest(string1.as_str(), string2.as_str());
        println!("The longest string is {}", result);
    }
    // result 不能再这里使用,因为 string2 的生命周期结束了
    
    let novel = String::from("Call me Ishmael. Some years ago...");
    let first_sentence = novel.split('.').next().expect("Could not find a '.'");
    let i = ImportantExcerpt {
        part: first_sentence,
    };
}

第八章:集合类型

8.1 Vector

rust 复制代码
fn vector_demo() {
    // 创建 Vector
    let v: Vec<i32> = Vec::new();
    let v = vec![1, 2, 3];  // 使用宏
    
    // 更新 Vector
    let mut v = Vec::new();
    v.push(5);
    v.push(6);
    v.push(7);
    v.push(8);
    
    // 读取元素
    let third: &i32 = &v[2];
    println!("The third element is {}", third);
    
    match v.get(2) {
        Some(third) => println!("The third element is {}", third),
        None => println!("There is no third element."),
    }
    
    // 迭代
    for i in &v {
        println!("{}", i);
    }
    
    // 迭代并修改
    for i in &mut v {
        *i += 50;
    }
    
    // 使用枚举存储多种类型
    enum SpreadsheetCell {
        Int(i32),
        Float(f64),
        Text(String),
    }
    
    let row = vec![
        SpreadsheetCell::Int(3),
        SpreadsheetCell::Text(String::from("blue")),
        SpreadsheetCell::Float(10.12),
    ];
}

8.2 String

rust 复制代码
fn string_demo() {
    // 创建字符串
    let mut s = String::new();
    let data = "initial contents";
    let s = data.to_string();
    let s = String::from("initial contents");
    
    // 更新字符串
    let mut s = String::from("foo");
    s.push_str("bar");
    s.push('!');
    
    // 字符串连接
    let s1 = String::from("Hello, ");
    let s2 = String::from("world!");
    let s3 = s1 + &s2;  // 注意 s1 被移动了,不能再被使用
    
    // 使用 format! 宏
    let s1 = String::from("tic");
    let s2 = String::from("tac");
    let s3 = String::from("toe");
    let s = format!("{}-{}-{}", s1, s2, s3);
    
    // 字符串索引
    let hello = "Здравствуйте";
    // let answer = &hello[0];  // 编译错误!
    
    // 字符串切片(字节位置)
    let s = &hello[0..4];  // 前4个字节
    println!("{}", s);  // 打印 "Зд"
    
    // 遍历字符
    for c in "नमस्ते".chars() {
        println!("{}", c);
    }
    
    // 遍历字节
    for b in "नमस्ते".bytes() {
        println!("{}", b);
    }
}

8.3 HashMap

rust 复制代码
use std::collections::HashMap;

fn hashmap_demo() {
    // 创建 HashMap
    let mut scores = HashMap::new();
    
    // 插入值
    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);
    
    // 访问值
    let team_name = String::from("Blue");
    let score = scores.get(&team_name);
    
    // 遍历
    for (key, value) in &scores {
        println!("{}: {}", key, value);
    }
    
    // 更新 HashMap
    scores.insert(String::from("Blue"), 25);  // 覆盖
    
    // 只在键不存在时插入
    scores.entry(String::from("Yellow")).or_insert(50);
    scores.entry(String::from("Red")).or_insert(50);
    
    // 根据旧值更新
    let text = "hello world wonderful world";
    let mut map = HashMap::new();
    
    for word in text.split_whitespace() {
        let count = map.entry(word).or_insert(0);
        *count += 1;
    }
    
    println!("{:?}", map);
}

第九章:智能指针

9.1 Box - 在堆上分配数据

rust 复制代码
fn box_demo() {
    // 在堆上分配一个 i32
    let b = Box::new(5);
    println!("b = {}", b);
    
    // 递归类型需要使用 Box
    #[derive(Debug)]
    enum List {
        Cons(i32, Box<List>),
        Nil,
    }
    
    use List::{Cons, Nil};
    
    let list = Cons(1, 
        Box::new(Cons(2, 
            Box::new(Cons(3, 
                Box::new(Nil))))));
    
    println!("{:?}", list);
}

9.2 Deref 和 Drop 特质

rust 复制代码
use std::ops::Deref;

// 自定义智能指针
struct MyBox<T>(T);

impl<T> MyBox<T> {
    fn new(x: T) -> MyBox<T> {
        MyBox(x)
    }
}

impl<T> Deref for MyBox<T> {
    type Target = T;
    
    fn deref(&self) -> &T {
        &self.0
    }
}

// 自定义 Drop 实现
struct CustomSmartPointer {
    data: String,
}

impl Drop for CustomSmartPointer {
    fn drop(&mut self) {
        println!("Dropping CustomSmartPointer with data `{}`!", self.data);
    }
}

fn deref_drop_demo() {
    let x = 5;
    let y = MyBox::new(x);
    
    assert_eq!(5, x);
    assert_eq!(5, *y);  // 解引用强制多态
    
    let c = CustomSmartPointer {
        data: String::from("my stuff"),
    };
    let d = CustomSmartPointer {
        data: String::from("other stuff"),
    };
    println!("CustomSmartPointers created.");
    // c 和 d 离开作用域时,会自动调用 drop
}

9.3 Rc - 引用计数智能指针

rust 复制代码
use std::rc::Rc;

fn rc_demo() {
    #[derive(Debug)]
    enum List {
        Cons(i32, Rc<List>),
        Nil,
    }
    
    use List::{Cons, Nil};
    
    let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil)))));
    println!("count after creating a = {}", Rc::strong_count(&a));
    
    let b = Cons(3, Rc::clone(&a));
    println!("count after creating b = {}", Rc::strong_count(&a));
    
    {
        let c = Cons(4, Rc::clone(&a));
        println!("count after creating c = {}", Rc::strong_count(&a));
    }
    
    println!("count after c goes out of scope = {}", Rc::strong_count(&a));
}

9.4 RefCell 和内部可变性模式

rust 复制代码
use std::cell::RefCell;

pub trait Messenger {
    fn send(&self, msg: &str);
}

struct MockMessenger {
    sent_messages: RefCell<Vec<String>>,
}

impl MockMessenger {
    fn new() -> MockMessenger {
        MockMessenger {
            sent_messages: RefCell::new(vec![]),
        }
    }
}

impl Messenger for MockMessenger {
    fn send(&self, message: &str) {
        self.sent_messages.borrow_mut().push(String::from(message));
    }
}

fn refcell_demo() {
    let mock_messenger = MockMessenger::new();
    mock_messenger.send("Hello");
    mock_messenger.send("World");
    
    let messages = mock_messenger.sent_messages.borrow();
    println!("Sent messages: {:?}", messages);
}

9.5 引用循环与内存泄漏

rust 复制代码
use std::rc::Rc;
use std::cell::RefCell;

fn reference_cycle_demo() {
    #[derive(Debug)]
    enum List {
        Cons(i32, RefCell<Rc<List>>),
        Nil,
    }
    
    impl List {
        fn tail(&self) -> Option<&RefCell<Rc<List>>> {
            match self {
                Cons(_, item) => Some(item),
                Nil => None,
            }
        }
    }
    
    use List::{Cons, Nil};
    
    let a = Rc::new(Cons(5, RefCell::new(Rc::new(Nil))));
    println!("a initial rc count = {}", Rc::strong_count(&a));
    println!("a next item = {:?}", a.tail());
    
    let b = Rc::new(Cons(10, RefCell::new(Rc::clone(&a))));
    println!("a rc count after b creation = {}", Rc::strong_count(&a));
    println!("b initial rc count = {}", Rc::strong_count(&b));
    println!("b next item = {:?}", b.tail());
    
    if let Some(link) = a.tail() {
        *link.borrow_mut() = Rc::clone(&b);
    }
    
    println!("b rc count after changing a = {}", Rc::strong_count(&b));
    println!("a rc count after changing a = {}", Rc::strong_count(&a));
    
    // 取消下面的注释会看到栈溢出
    // println!("a next item = {:?}", a.tail());
}

第十章:并发编程

10.1 使用线程

rust 复制代码
use std::thread;
use std::time::Duration;

fn thread_demo() {
    // 创建新线程
    let handle = thread::spawn(|| {
        for i in 1..10 {
            println!("hi number {} from the spawned thread!", i);
            thread::sleep(Duration::from_millis(1));
        }
    });
    
    for i in 1..5 {
        println!("hi number {} from the main thread!", i);
        thread::sleep(Duration::from_millis(1));
    }
    
    handle.join().unwrap();
    
    // 使用 move 闭包
    let v = vec![1, 2, 3];
    
    let handle = thread::spawn(move || {
        println!("Here's a vector: {:?}", v);
    });
    
    handle.join().unwrap();
}

10.2 消息传递并发

rust 复制代码
use std::sync::mpsc;
use std::thread;

fn message_passing_demo() {
    // 创建通道
    let (tx, rx) = mpsc::channel();
    
    // 克隆发送端
    let tx1 = tx.clone();
    
    thread::spawn(move || {
        let vals = vec![
            String::from("hi"),
            String::from("from"),
            String::from("the"),
            String::from("thread"),
        ];
        
        for val in vals {
            tx1.send(val).unwrap();
            thread::sleep(Duration::from_millis(100));
        }
    });
    
    thread::spawn(move || {
        let vals = vec![
            String::from("more"),
            String::from("messages"),
            String::from("for"),
            String::from("you"),
        ];
        
        for val in vals {
            tx.send(val).unwrap();
            thread::sleep(Duration::from_millis(100));
        }
    });
    
    // 在主线程中接收
    for received in rx {
        println!("Got: {}", received);
    }
}

10.3 共享状态并发

rust 复制代码
use std::sync::{Mutex, Arc};
use std::thread;

fn shared_state_demo() {
    // 使用 Mutex
    let m = Mutex::new(5);
    
    {
        let mut num = m.lock().unwrap();
        *num = 6;
    }
    
    println!("m = {:?}", m);
    
    // 多线程共享 Mutex
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];
    
    for _ in 0..10 {
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();
            *num += 1;
        });
        handles.push(handle);
    }
    
    for handle in handles {
        handle.join().unwrap();
    }
    
    println!("Result: {}", *counter.lock().unwrap());
}

10.4 Sync 和 Send 特质

rust 复制代码
use std::thread;

// Send 和 Sync 是自动实现的特质
// 大多数类型都是 Send 和 Sync 的

fn sync_send_demo() {
    // Rc<T> 不是 Send 的,所以不能跨线程传递
    // let rc = Rc::new(5);
    // thread::spawn(move || {
    //     println!("{}", rc);
    // });  // 编译错误!
    
    // 但 Arc<T> 是 Send 和 Sync 的
    use std::sync::Arc;
    let arc = Arc::new(5);
    let arc_clone = Arc::clone(&arc);
    
    thread::spawn(move || {
        println!("{}", arc_clone);
    }).join().unwrap();
    
    println!("{}", arc);
}

第十一章:高级特性

11.1 不安全 Rust

rust 复制代码
fn unsafe_demo() {
    // 解引用裸指针
    let mut num = 5;
    
    let r1 = &num as *const i32;
    let r2 = &mut num as *mut i32;
    
    unsafe {
        println!("r1 is: {}", *r1);
        println!("r2 is: {}", *r2);
    }
    
    // 调用不安全函数
    unsafe fn dangerous() {}
    
    unsafe {
        dangerous();
    }
    
    // 创建不安全代码的安全抽象
    fn split_at_mut(slice: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
        let len = slice.len();
        let ptr = slice.as_mut_ptr();
        
        assert!(mid <= len);
        
        unsafe {
            (
                std::slice::from_raw_parts_mut(ptr, mid),
                std::slice::from_raw_parts_mut(ptr.add(mid), len - mid),
            )
        }
    }
    
    let mut v = vec![1, 2, 3, 4, 5, 6];
    let (left, right) = split_at_mut(&mut v, 3);
    println!("left: {:?}, right: {:?}", left, right);
    
    // 使用 extern 函数调用外部代码
    extern "C" {
        fn abs(input: i32) -> i32;
    }
    
    unsafe {
        println!("Absolute value of -3 according to C: {}", abs(-3));
    }
    
    // 访问或修改可变静态变量
    static mut COUNTER: u32 = 0;
    
    fn add_to_count(inc: u32) {
        unsafe {
            COUNTER += inc;
        }
    }
    
    add_to_count(3);
    
    unsafe {
        println!("COUNTER: {}", COUNTER);
    }
    
    // 实现不安全特质
    unsafe trait Foo {
        // 方法定义
    }
    
    unsafe impl Foo for i32 {
        // 方法实现
    }
}

11.2 高级特质

rust 复制代码
// 关联类型
pub trait Iterator {
    type Item;
    
    fn next(&mut self) -> Option<Self::Item>;
}

// 默认泛型类型参数和运算符重载
use std::ops::Add;

#[derive(Debug, Copy, Clone, PartialEq)]
struct Point {
    x: i32,
    y: i32,
}

impl Add for Point {
    type Output = Point;
    
    fn add(self, other: Point) -> Point {
        Point {
            x: self.x + other.x,
            y: self.y + other.y,
        }
    }
}

// 完全限定语法用于消除歧义
trait Pilot {
    fn fly(&self);
}

trait Wizard {
    fn fly(&self);
}

struct Human;

impl Pilot for Human {
    fn fly(&self) {
        println!("This is your captain speaking.");
    }
}

impl Wizard for Human {
    fn fly(&self) {
        println!("Up!");
    }
}

impl Human {
    fn fly(&self) {
        println!("*waving arms furiously*");
    }
}

fn advanced_traits_demo() {
    let person = Human;
    person.fly();  // 调用 Human 的 fly
    
    Pilot::fly(&person);
    Wizard::fly(&person);
    
    // 父特质
    trait OutlinePrint: std::fmt::Display {
        fn outline_print(&self) {
            let output = self.to_string();
            let len = output.len();
            println!("{}", "*".repeat(len + 4));
            println!("*{}*", " ".repeat(len + 2));
            println!("* {} *", output);
            println!("*{}*", " ".repeat(len + 2));
            println!("{}", "*".repeat(len + 4));
        }
    }
    
    // newtype 模式
    struct Wrapper(Vec<String>);
    
    impl std::fmt::Display for Wrapper {
        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            write!(f, "[{}]", self.0.join(", "))
        }
    }
}

11.3 高级类型

rust 复制代码
fn advanced_types_demo() {
    // 类型别名
    type Kilometers = i32;
    
    let x: i32 = 5;
    let y: Kilometers = 5;
    
    println!("x + y = {}", x + y);
    
    // Never 类型 (!)
    fn never_returns() -> ! {
        loop {
            println!("I never return!");
        }
    }
    
    // 动态大小类型和 Sized 特质
    fn generic<T: ?Sized>(t: &T) {
        // 函数体
    }
}

11.4 高级函数与闭包

rust 复制代码
fn advanced_functions_demo() {
    // 函数指针
    fn add_one(x: i32) -> i32 {
        x + 1
    }
    
    fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 {
        f(arg) + f(arg)
    }
    
    let answer = do_twice(add_one, 5);
    println!("The answer is: {}", answer);
    
    // 返回闭包
    fn returns_closure() -> Box<dyn Fn(i32) -> i32> {
        Box::new(|x| x + 1)
    }
    
    let closure = returns_closure();
    println!("{}", closure(5));
}

第十二章:宏

12.1 声明宏

rust 复制代码
// 简单的声明宏
macro_rules! vec {
    ( $( $x:expr ),* ) => {
        {
            let mut temp_vec = Vec::new();
            $(
                temp_vec.push($x);
            )*
            temp_vec
        }
    };
}

fn declarative_macros_demo() {
    let v = vec![1, 2, 3];
    println!("{:?}", v);
}

// 更复杂的宏
macro_rules! calculate {
    (eval $e:expr) => {{
        {
            let val: usize = $e;
            println!("{} = {}", stringify!($e), val);
        }
    }};
    
    (eval $e:expr, $(eval $es:expr),+) => {{
        calculate! { eval $e }
        calculate! { $(eval $es),+ }
    }};
}

fn complex_macro_demo() {
    calculate! {
        eval 1 + 2,
        eval 3 + 4,
        eval (2 * 3) + 1
    }
}

12.2 过程宏

rust 复制代码
// 注意:过程宏需要在独立的 crate 中定义
// 这里只是展示用法示例

/*
// 在 Cargo.toml 中:
[lib]
proc-macro = true

// 在 lib.rs 中:
use proc_macro::TokenStream;
use quote::quote;
use syn;

#[proc_macro_derive(HelloMacro)]
pub fn hello_macro_derive(input: TokenStream) -> TokenStream {
    let ast = syn::parse(input).unwrap();
    impl_hello_macro(&ast)
}

fn impl_hello_macro(ast: &syn::DeriveInput) -> TokenStream {
    let name = &ast.ident;
    let gen = quote! {
        impl HelloMacro for #name {
            fn hello_macro() {
                println!("Hello, Macro! My name is {}!", stringify!(#name));
            }
        }
    };
    gen.into()
}
*/

// 使用过程宏
/*
use hello_macro::HelloMacro;

#[derive(HelloMacro)]
struct Pancakes;

fn procedural_macro_demo() {
    Pancakes::hello_macro();
}
*/

第十三章:实战项目 - 构建简单的 Web 服务器

13.1 项目结构

复制代码
webserver/
├── Cargo.toml
└── src/
    ├── main.rs
    ├── lib.rs
    ├── thread_pool.rs
    └── http/
        ├── mod.rs
        ├── request.rs
        └── response.rs

13.2 线程池实现

rust 复制代码
// src/thread_pool.rs
use std::sync::{mpsc, Arc, Mutex};
use std::thread;

type Job = Box<dyn FnOnce() + Send + 'static>;

pub struct ThreadPool {
    workers: Vec<Worker>,
    sender: mpsc::Sender<Job>,
}

impl ThreadPool {
    /// 创建线程池。
    ///
    /// size 是线程池中的线程数。
    ///
    /// # Panics
    ///
    /// `new` 函数在 size 为 0 时会 panic。
    pub fn new(size: usize) -> ThreadPool {
        assert!(size > 0);

        let (sender, receiver) = mpsc::channel();
        let receiver = Arc::new(Mutex::new(receiver));

        let mut workers = Vec::with_capacity(size);

        for id in 0..size {
            workers.push(Worker::new(id, Arc::clone(&receiver)));
        }

        ThreadPool { workers, sender }
    }

    pub fn execute<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
        let job = Box::new(f);
        self.sender.send(job).unwrap();
    }
}

struct Worker {
    id: usize,
    thread: thread::JoinHandle<()>,
}

impl Worker {
    fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
        let thread = thread::spawn(move || loop {
            let job = receiver.lock().unwrap().recv().unwrap();
            println!("Worker {} got a job; executing.", id);
            job();
        });

        Worker { id, thread }
    }
}

13.3 HTTP 模块

rust 复制代码
// src/http/mod.rs
pub mod request;
pub mod response;

pub use request::Request;
pub use response::Response;
rust 复制代码
// src/http/request.rs
use std::collections::HashMap;
use std::convert::TryFrom;
use std::error::Error;
use std::fmt;

#[derive(Debug)]
pub struct Request {
    pub method: String,
    pub path: String,
    pub headers: HashMap<String, String>,
    pub body: String,
}

#[derive(Debug)]
pub struct ParseError;

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Failed to parse HTTP request")
    }
}

impl Error for ParseError {}

impl TryFrom<&str> for Request {
    type Error = ParseError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        let mut lines = value.lines();
        
        // 解析请求行
        let request_line = lines.next().ok_or(ParseError)?;
        let mut parts = request_line.split_whitespace();
        let method = parts.next().ok_or(ParseError)?.to_string();
        let path = parts.next().ok_or(ParseError)?.to_string();
        
        // 解析头部
        let mut headers = HashMap::new();
        for line in lines.by_ref() {
            if line.is_empty() {
                break;
            }
            
            if let Some((key, value)) = line.split_once(':') {
                headers.insert(
                    key.trim().to_string(),
                    value.trim().to_string(),
                );
            }
        }
        
        // 解析主体
        let body = lines.collect::<Vec<&str>>().join("\n");
        
        Ok(Request {
            method,
            path,
            headers,
            body,
        })
    }
}
rust 复制代码
// src/http/response.rs
use std::collections::HashMap;
use std::fmt;

pub struct Response {
    pub status_code: u16,
    pub headers: HashMap<String, String>,
    pub body: String,
}

impl Response {
    pub fn new(status_code: u16, body: String) -> Self {
        let mut headers = HashMap::new();
        headers.insert("Content-Type".to_string(), "text/html".to_string());
        headers.insert("Content-Length".to_string(), body.len().to_string());
        
        Response {
            status_code,
            headers,
            body,
        }
    }
    
    pub fn ok(body: String) -> Self {
        Self::new(200, body)
    }
    
    pub fn not_found() -> Self {
        Self::new(404, String::from("404 Not Found"))
    }
}

impl fmt::Display for Response {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // 状态行
        let status_line = match self.status_code {
            200 => "HTTP/1.1 200 OK",
            404 => "HTTP/1.1 404 Not Found",
            _ => "HTTP/1.1 500 Internal Server Error",
        };
        
        write!(f, "{}\r\n", status_line)?;
        
        // 头部
        for (key, value) in &self.headers {
            write!(f, "{}: {}\r\n", key, value)?;
        }
        
        // 空行分隔头部和主体
        write!(f, "\r\n")?;
        
        // 主体
        write!(f, "{}", self.body)
    }
}

13.4 主程序

rust 复制代码
// src/main.rs
use std::io::prelude::*;
use std::net::{TcpListener, TcpStream};
use std::time::Duration;
use std::{fs, thread};

use webserver::ThreadPool;
use webserver::http::{Request, Response};

fn main() {
    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
    let pool = ThreadPool::new(4);
    
    println!("Server running on http://127.0.0.1:7878");
    
    for stream in listener.incoming().take(2) {
        let stream = stream.unwrap();
        
        pool.execute(|| {
            handle_connection(stream);
        });
    }
    
    println!("Shutting down.");
}

fn handle_connection(mut stream: TcpStream) {
    let mut buffer = [0; 1024];
    stream.read(&mut buffer).unwrap();
    
    let request = String::from_utf8_lossy(&buffer[..]);
    println!("Request: {}", request);
    
    let response = match Request::try_from(request.as_ref()) {
        Ok(req) => handle_request(req),
        Err(_) => Response::new(400, String::from("Bad Request")),
    };
    
    stream.write(response.to_string().as_bytes()).unwrap();
    stream.flush().unwrap();
}

fn handle_request(request: Request) -> Response {
    match (request.method.as_str(), request.path.as_str()) {
        ("GET", "/") => Response::ok(get_contents("hello.html")),
        ("GET", "/sleep") => {
            thread::sleep(Duration::from_secs(5));
            Response::ok(get_contents("hello.html"))
        }
        _ => Response::not_found(),
    }
}

fn get_contents(filename: &str) -> String {
    fs::read_to_string(filename).unwrap_or_else(|_| {
        String::from("<!DOCTYPE html><html><body><h1>Hello!</h1></body></html>")
    })
}
rust 复制代码
// src/lib.rs
pub mod thread_pool;
pub mod http;

pub use thread_pool::ThreadPool;

第十四章:测试与文档

14.1 单元测试

rust 复制代码
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        let result = 2 + 2;
        assert_eq!(result, 4);
    }

    #[test]
    fn larger_can_hold_smaller() {
        let larger = Rectangle {
            width: 8,
            height: 7,
        };
        let smaller = Rectangle {
            width: 5,
            height: 1,
        };

        assert!(larger.can_hold(&smaller));
    }

    #[test]
    #[should_panic(expected = "Guess value must be between 1 and 100")]
    fn greater_than_100() {
        Guess::new(200);
    }

    #[test]
    fn it_works_with_result() -> Result<(), String> {
        if 2 + 2 == 4 {
            Ok(())
        } else {
            Err(String::from("two plus two does not equal four"))
        }
    }
}

14.2 集成测试

rust 复制代码
// tests/integration_test.rs
use webserver::ThreadPool;

#[test]
fn test_thread_pool_creation() {
    let pool = ThreadPool::new(4);
    assert_eq!(pool.workers.len(), 4);
}

14.3 文档测试

rust 复制代码
/// 将两个数字相加
///
/// # Examples
///
/// ```
/// use my_crate::add;
///
/// assert_eq!(add(2, 2), 4);
/// ```
///
/// # Panics
///
/// 这个函数不会 panic
///
/// # Errors
///
/// 这个函数不会返回错误
///
/// # Safety
///
/// 这个函数是安全的
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

/// 一个表示矩形的结构体
///
/// # Examples
///
/// ```
/// use my_crate::Rectangle;
///
/// let rect = Rectangle::new(10, 20);
/// assert_eq!(rect.area(), 200);
/// ```
#[derive(Debug)]
pub struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    /// 创建一个新的矩形
    pub fn new(width: u32, height: u32) -> Self {
        Rectangle { width, height }
    }
    
    /// 计算矩形的面积
    pub fn area(&self) -> u32 {
        self.width * self.height
    }
}

第十五章:性能优化与最佳实践

15.1 性能优化技巧

rust 复制代码
fn performance_optimization() {
    // 1. 使用合适的集合类型
    // 对于大量数据,考虑使用 VecDeque 或 LinkedList
    
    // 2. 避免不必要的克隆
    let s = String::from("hello");
    process_string(&s);  // 使用引用而不是克隆
    
    // 3. 使用容量提示
    let mut v = Vec::with_capacity(1000);
    
    // 4. 使用迭代器而不是手动循环
    let sum: i32 = (1..1000).filter(|&x| x % 2 == 0).sum();
    
    // 5. 使用 Cow(Copy on Write)智能指针
    use std::borrow::Cow;
    fn process_data(data: &str) -> Cow<str> {
        if data.contains("special") {
            Cow::Owned(data.to_uppercase())
        } else {
            Cow::Borrowed(data)
        }
    }
    
    // 6. 使用 Box<[T]> 而不是 Vec<T> 当大小固定时
    let boxed_slice: Box<[i32]> = vec![1, 2, 3].into_boxed_slice();
    
    // 7. 使用 #[inline] 提示编译器内联小函数
    #[inline]
    fn add_one(x: i32) -> i32 {
        x + 1
    }
}

fn process_string(s: &str) {
    println!("Processing: {}", s);
}

15.2 内存管理最佳实践

rust 复制代码
fn memory_management() {
    // 1. 使用栈分配当可能时
    let x = 5;  // 栈分配
    
    // 2. 使用适当的智能指针
    // - Box<T>: 单一所有权,堆分配
    // - Rc<T>: 多所有权,不可变引用
    // - Arc<T>: 线程安全的多所有权
    // - RefCell<T>: 内部可变性
    
    // 3. 避免引用循环
    use std::rc::{Rc, Weak};
    
    struct Node {
        value: i32,
        parent: Option<Weak<Node>>,
        children: Vec<Rc<Node>>,
    }
    
    // 4. 使用 arenas 用于大量小对象分配
    // 考虑使用 bumpalo 或 typed-arena crate
    
    // 5. 使用对象池模式
    struct ObjectPool {
        objects: Vec<ReusableObject>,
    }
    
    impl ObjectPool {
        fn get(&mut self) -> ReusableObject {
            self.objects.pop().unwrap_or_else(ReusableObject::new)
        }
        
        fn return_obj(&mut self, obj: ReusableObject) {
            obj.reset();
            self.objects.push(obj);
        }
    }
    
    struct ReusableObject {
        data: String,
    }
    
    impl ReusableObject {
        fn new() -> Self {
            ReusableObject { data: String::new() }
        }
        
        fn reset(&mut self) {
            self.data.clear();
        }
    }
}

结语

通过本文的深入学习,您已经掌握了 Rust 编程语言的核心概念和高级特性。从基础语法到所有权系统,从并发编程到元编程,Rust 提供了一套完整且强大的工具集,帮助您编写安全、高效的系统级软件。

Rust 的学习曲线虽然相对陡峭,但其带来的安全性保证和性能优势使得这一投入物有所值。随着对语言的深入理解,您会发现 Rust 的严格性实际上是一种保护,它迫使您在编译时解决潜在的问题,而不是在运行时遇到难以调试的错误。

继续深入学习 Rust 的建议:

  1. 阅读《The Rust Programming Language》(Rust 官方书籍)
  2. 参与开源 Rust 项目
  3. 关注 Rust 官方博客和 RFC
  4. 加入 Rust 社区参与讨论
  5. 实践更多的项目,将理论知识转化为实际经验
    另外还有
    新手入门指南:https://xuanwu.openatom.cn/guide/quick-start/install.html
    在线体验:https://xuanwu.openatom.cn/rust-playground/
    Rust算法案例:https://gitcode.com/GitHub_Trending/rus/Rust
    Rust工程示例:https://doc.rust-lang.org/rust-by-example/index.html

Rust 正在改变系统编程的面貌,为构建可靠、高效的软件提供了新的可能。希望本文能为您的 Rust 学习之旅奠定坚实的基础!

相关推荐
没有故事、有酒3 小时前
Axios
开发语言·php
xiaozaq3 小时前
java 正则表达式 所有的优先级
java·开发语言·正则表达式
JMzz3 小时前
Rust 中的数据结构选择与性能影响:从算法复杂度到硬件特性 [特殊字符]
开发语言·数据结构·后端·算法·性能优化·rust
鹿鸣天涯3 小时前
等保测评取消打分,《网络安全等级测评报告模版(2025版)》重大变更,详细解读两细化、三变更、五新增
网络·安全·web安全
钟离墨笺3 小时前
Go语言-->sync.WaitGroup 详细解释
开发语言·后端·golang
小L~~~3 小时前
Python打造美观的桌面温馨提醒弹窗
开发语言·python
汤姆yu3 小时前
基于python大数据的特产推荐系统
大数据·开发语言·python
四念处茫茫3 小时前
仓颉技术:FFI外部函数接口
开发语言·后端·仓颉技术
ColderYY4 小时前
Python中的正则表达式
开发语言·python·正则表达式