Rust高级类型与零成本抽象实战

Rust的类型系统是其最强大的特性之一,提供了无与伦比的表达能力和安全性。本章将深入探索高级类型特性、零成本抽象和函数式编程模式,帮助你编写更优雅、更安全的Rust代码。

第三十五章:高级类型特性

35.1 关联类型和GATs(通用关联类型)

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

// 自定义集合trait
trait Collection {
    type Item;
    type Iter: Iterator<Item = Self::Item>;
    
    fn iter(&self) -> Self::Iter;
    fn len(&self) -> usize;
    fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

// 为Vec实现Collection
impl<T> Collection for Vec<T> {
    type Item = T;
    type Iter = std::vec::IntoIter<T>;
    
    fn iter(&self) -> Self::Iter {
        self.clone().into_iter()
    }
    
    fn len(&self) -> usize {
        self.len()
    }
}

// 通用关联类型 (GATs) 示例
trait LendingIterator {
    type Item<'a> where Self: 'a;
    
    fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;
}

struct Windows<'a, T> {
    data: &'a [T],
    size: usize,
    index: usize,
}

impl<'a, T> LendingIterator for Windows<'a, T> {
    type Item<'b> = &'b [T] where Self: 'b;
    
    fn next<'b>(&'b mut self) -> Option<Self::Item<'b>> {
        if self.index + self.size <= self.data.len() {
            let window = &self.data[self.index..self.index + self.size];
            self.index += 1;
            Some(window)
        } else {
            None
        }
    }
}

// 高级类型边界
trait AdvancedBounds {
    type Associated;
    
    // 要求Associated类型实现Debug和Clone
    fn process(&self) -> Self::Associated
    where
        Self::Associated: std::fmt::Debug + Clone;
}

#[derive(Debug, Clone)]
struct ProcessResult(String);

impl AdvancedBounds for String {
    type Associated = ProcessResult;
    
    fn process(&self) -> Self::Associated {
        ProcessResult(format!("处理: {}", self))
    }
}

fn main() {
    println!("=== 高级类型特性 ===");
    
    // 关联类型使用
    let vec = vec![1, 2, 3];
    let mut iter = vec.iter();
    while let Some(item) = iter.next() {
        println!("项: {}", item);
    }
    
    // GATs使用
    let data = [1, 2, 3, 4, 5];
    let mut windows = Windows {
        data: &data,
        size: 3,
        index: 0,
    };
    
    while let Some(window) = windows.next() {
        println!("窗口: {:?}", window);
    }
    
    // 高级边界使用
    let result = "hello".to_string().process();
    println!("处理结果: {:?}", result);
}

35.2 高阶Trait边界(HRTB)

rust 复制代码
// 高阶Trait边界示例
trait Closure<Args> {
    type Output;
    
    fn call(&self, args: Args) -> Self::Output;
}

// 使用HRTB表示闭包生命周期
fn apply_closure<'a, F>(f: F, value: &'a str) -> F::Output
where
    F: for<'b> Closure<(&'b str,), Output = String>,
{
    f.call((value,))
}

// 实际闭包实现
impl<F, Args, Output> Closure<Args> for F
where
    F: Fn(Args) -> Output,
{
    type Output = Output;
    
    fn call(&self, args: Args) -> Self::Output {
        self(args)
    }
}

// 更复杂的HRTB示例
trait Reference {
    type Value;
    
    fn get(&self) -> &Self::Value;
}

struct Container<T> {
    value: T,
}

impl<T> Reference for Container<T> {
    type Value = T;
    
    fn get(&self) -> &Self::Value {
        &self.value
    }
}

// 接受任何引用类型的函数
fn process_reference<R>(reference: R) -> String
where
    R: for<'a> Reference<Value = &'a str>,
{
    reference.get().to_uppercase()
}

// 生命周期子类型
fn longest<'a, 'b: 'a>(x: &'a str, y: &'b str) -> &'a str {
    if x.len() > y.len() { x } else { y }
}

#[cfg(test)]
mod hrtb_tests {
    use super::*;

    #[test]
    fn test_closure_application() {
        let closure = |s: &str| format!("处理: {}", s);
        let result = apply_closure(closure, "test");
        assert_eq!(result, "处理: test");
    }

    #[test]
    fn test_reference_processing() {
        let container = Container { value: "hello" };
        let result = process_reference(container);
        assert_eq!(result, "HELLO");
    }
}

fn main() {
    println!("=== 高阶Trait边界 ===");
    
    // 闭包应用
    let greeting = |name: &str| format!("Hello, {}!", name);
    let result = apply_closure(greeting, "World");
    println!("{}", result);
    
    // 引用处理
    let text_container = Container { value: "rust programming" };
    let processed = process_reference(text_container);
    println!("处理后的文本: {}", processed);
    
    // 生命周期子类型
    let s1 = "短字符串";
    let s2 = "这是一个较长的字符串";
    let longest_str = longest(s1, s2);
    println!("较长的字符串: {}", longest_str);
}

第三十六章:零成本抽象

36.1 泛型编程和特化

rust 复制代码
use std::ops::{Add, Mul};

// 通用数学运算trait
trait MathOps<T> {
    fn square(&self) -> T;
    fn cube(&self) -> T;
    fn power(&self, exponent: u32) -> T;
}

// 为所有数字类型实现MathOps
impl<T> MathOps<T> for T
where
    T: Copy + Mul<Output = T> + Add<Output = T> + From<u8>,
{
    fn square(&self) -> T {
        *self * *self
    }
    
    fn cube(&self) -> T {
        *self * *self * *self
    }
    
    fn power(&self, exponent: u32) -> T {
        if exponent == 0 {
            return T::from(1);
        }
        
        let mut result = *self;
        for _ in 1..exponent {
            result = result * *self;
        }
        result
    }
}

// 性能优化的特化版本
trait FastMath {
    fn fast_power(&self, exponent: u32) -> Self;
}

impl FastMath for i32 {
    fn fast_power(&self, exponent: u32) -> Self {
        self.pow(exponent)
    }
}

impl FastMath for f64 {
    fn fast_power(&self, exponent: u32) -> Self {
        self.powi(exponent as i32)
    }
}

// 编译时多态
struct Calculator;

impl Calculator {
    fn compute<T>(&self, x: T) -> T
    where
        T: MathOps<T> + FastMath + Copy,
    {
        x.square() + x.cube()
    }
    
    fn compute_fast<T>(&self, x: T, exponent: u32) -> T
    where
        T: FastMath + Copy,
    {
        x.fast_power(exponent)
    }
}

// 零成本错误处理
trait FallibleOperation {
    type Output;
    type Error;
    
    fn execute(&self) -> Result<Self::Output, Self::Error>;
}

struct SafeDivisor {
    numerator: i32,
    denominator: i32,
}

impl FallibleOperation for SafeDivisor {
    type Output = i32;
    type Error = String;
    
    fn execute(&self) -> Result<Self::Output, Self::Error> {
        if self.denominator == 0 {
            Err("除零错误".to_string())
        } else {
            Ok(self.numerator / self.denominator)
        }
    }
}

fn main() {
    println!("=== 零成本抽象 ===");
    
    let calculator = Calculator;
    
    // 泛型计算
    let int_result = calculator.compute(5);
    println!("整数计算: {}", int_result);
    
    let float_result = calculator.compute(2.5);
    println!("浮点数计算: {}", float_result);
    
    // 快速计算
    let fast_result = calculator.compute_fast(2, 10);
    println!("快速幂运算: {}", fast_result);
    
    // 错误处理
    let divisor = SafeDivisor {
        numerator: 10,
        denominator: 2,
    };
    
    match divisor.execute() {
        Ok(result) => println!("除法结果: {}", result),
        Err(e) => println!("错误: {}", e),
    }
    
    // 编译时优化演示
    compile_time_optimization();
}

fn compile_time_optimization() {
    println!("\n=== 编译时优化 ===");
    
    // 这些调用在编译时会被单态化,生成特定类型的优化代码
    let functions: Vec<fn(i32) -> i32> = vec![
        |x| x.square(),
        |x| x.cube(),
        |x| x.power(4),
    ];
    
    for (i, func) in functions.iter().enumerate() {
        let result = func(3);
        println!("函数 {} 结果: {}", i, result);
    }
}

36.2 类型级编程

rust 复制代码
use std::marker::PhantomData;

// 类型级数字
trait TypeNumber {
    const VALUE: u32;
}

struct Zero;
struct Succ<T>(PhantomData<T>);

impl TypeNumber for Zero {
    const VALUE: u32 = 0;
}

impl<T: TypeNumber> TypeNumber for Succ<T> {
    const VALUE: u32 = T::VALUE + 1;
}

// 类型级布尔
trait TypeBool {
    const VALUE: bool;
}

struct True;
struct False;

impl TypeBool for True {
    const VALUE: bool = true;
}

impl TypeBool for False {
    const VALUE: bool = false;
}

// 类型级链表
trait TypeList {
    type Head;
    type Tail: TypeList;
}

struct Nil;
struct Cons<H, T>(PhantomData<(H, T)>);

impl TypeList for Nil {
    type Head = ();
    type Tail = Nil;
}

impl<H, T: TypeList> TypeList for Cons<H, T> {
    type Head = H;
    type Tail = T;
}

// 类型级算术运算
trait Add<Rhs> {
    type Output;
}

impl<T: TypeNumber> Add<Zero> for T {
    type Output = T;
}

impl<T: TypeNumber, Rhs: TypeNumber> Add<Succ<Rhs>> for T
where
    T: Add<Rhs>,
    <T as Add<Rhs>>::Output: TypeNumber,
{
    type Output = Succ<<T as Add<Rhs>>::Output>;
}

// 实际应用:维度检查
struct Vector<T, Dim>(Vec<T>, PhantomData<Dim>);

impl<T, Dim: TypeNumber> Vector<T, Dim> {
    fn new() -> Self {
        Vector(Vec::new(), PhantomData)
    }
    
    fn push(&mut self, item: T) {
        self.0.push(item);
    }
    
    fn len(&self) -> u32 {
        Dim::VALUE
    }
}

// 安全的向量运算
trait DotProduct<Rhs> {
    type Output;
    
    fn dot(&self, other: &Rhs) -> Self::Output;
}

impl<T, Dim> DotProduct<Vector<T, Dim>> for Vector<T, Dim>
where
    T: Mul<Output = T> + Add<Output = T> + Copy + Default,
    Dim: TypeNumber,
{
    type Output = T;
    
    fn dot(&self, other: &Vector<T, Dim>) -> Self::Output {
        // 这里简化实现,实际应该检查维度匹配
        let mut result = T::default();
        for i in 0..self.0.len().min(other.0.len()) {
            result = result + self.0[i] * other.0[i];
        }
        result
    }
}

fn main() {
    println!("=== 类型级编程 ===");
    
    // 类型级数字
    type One = Succ<Zero>;
    type Two = Succ<One>;
    type Three = Succ<Two>;
    
    println!("类型级数字:");
    println!("Zero: {}", Zero::VALUE);
    println!("One: {}", One::VALUE);
    println!("Two: {}", Two::VALUE);
    println!("Three: {}", Three::VALUE);
    
    // 类型级算术
    type OnePlusTwo = <One as Add<Two>>::Output;
    println!("1 + 2 = {}", OnePlusTwo::VALUE);
    
    // 维度安全向量
    let mut vec2: Vector<i32, Two> = Vector::new();
    vec2.push(1);
    vec2.push(2);
    
    println!("二维向量长度: {}", vec2.len());
    
    let vec2_other: Vector<i32, Two> = Vector(vec![3, 4], PhantomData);
    let dot_result = vec2.dot(&vec2_other);
    println!("点积结果: {}", dot_result);
    
    // 编译时验证
    compile_time_validation();
}

fn compile_time_validation() {
    println!("\n=== 编译时验证 ===");
    
    // 这些代码会在编译时验证类型正确性
    // 以下代码如果取消注释会导致编译错误:
    
    // let vec2: Vector<i32, Two> = Vector::new();
    // let vec3: Vector<i32, Three> = Vector::new();
    // let _invalid = vec2.dot(&vec3); // 编译错误:维度不匹配
}

第三十七章:函数式编程模式

37.1 Monad和Functor

rust 复制代码
// Option的Functor和Monad实现
trait Functor<A> {
    type Output<B>: Functor<B>;
    
    fn map<B, F>(self, f: F) -> Self::Output<B>
    where
        F: FnOnce(A) -> B;
}

trait Monad<A>: Functor<A> {
    fn pure(value: A) -> Self;
    
    fn bind<B, F>(self, f: F) -> Self::Output<B>
    where
        F: FnOnce(A) -> Self::Output<B>;
}

impl<A> Functor<A> for Option<A> {
    type Output<B> = Option<B>;
    
    fn map<B, F>(self, f: F) -> Self::Output<B>
    where
        F: FnOnce(A) -> B,
    {
        self.map(f)
    }
}

impl<A> Monad<A> for Option<A> {
    fn pure(value: A) -> Self {
        Some(value)
    }
    
    fn bind<B, F>(self, f: F) -> Self::Output<B>
    where
        F: FnOnce(A) -> Self::Output<B>,
    {
        self.and_then(f)
    }
}

// Result的Monad实现
impl<A, E> Functor<A> for Result<A, E> {
    type Output<B> = Result<B, E>;
    
    fn map<B, F>(self, f: F) -> Self::Output<B>
    where
        F: FnOnce(A) -> B,
    {
        self.map(f)
    }
}

impl<A, E> Monad<A> for Result<A, E> {
    fn pure(value: A) -> Self {
        Ok(value)
    }
    
    fn bind<B, F>(self, f: F) -> Self::Output<B>
    where
        F: FnOnce(A) -> Self::Output<B>,
    {
        self.and_then(f)
    }
}

// 自定义Monad:State Monad
struct State<S, A>(Box<dyn Fn(S) -> (A, S)>);

impl<S, A> State<S, A> {
    fn run(self, state: S) -> (A, S) {
        self.0(state)
    }
}

impl<S, A> Functor<A> for State<S, A> {
    type Output<B> = State<S, B>;
    
    fn map<B, F>(self, f: F) -> Self::Output<B>
    where
        F: FnOnce(A) -> B,
    {
        State(Box::new(move |s| {
            let (a, s2) = self.run(s);
            (f(a), s2)
        }))
    }
}

impl<S, A> Monad<A> for State<S, A> {
    fn pure(value: A) -> Self {
        State(Box::new(move |s| (value, s)))
    }
    
    fn bind<B, F>(self, f: F) -> Self::Output<B>
    where
        F: FnOnce(A) -> Self::Output<B>,
    {
        State(Box::new(move |s| {
            let (a, s2) = self.run(s);
            f(a).run(s2)
        }))
    }
}

// Do Notation宏
macro_rules! do_monad {
    ($monad:expr => $bind:ident >>= $expr:expr) => {{
        let $bind = $monad;
        $expr
    }};
    
    ($monad:expr => $bind:ident >>= $expr:expr; $($rest:tt)*) => {{
        let $bind = $monad;
        do_monad!($expr => $($rest)*)
    }};
}

fn main() {
    println!("=== 函数式编程模式 ===");
    
    // Option Monad示例
    let result = Option::pure(5)
        .bind(|x| Some(x + 1))
        .bind(|x| Some(x * 2))
        .bind(|x| if x > 10 { Some(x) } else { None });
    
    println!("Option Monad结果: {:?}", result);
    
    // Result Monad示例
    let computation: Result<i32, &str> = Result::pure(5)
        .bind(|x| Ok(x + 3))
        .bind(|x| if x < 10 { Ok(x * 2) } else { Err("值太大") });
    
    println!("Result Monad结果: {:?}", computation);
    
    // State Monad示例
    let state_computation = State::pure(5)
        .bind(|x| State(Box::new(move |s: i32| (x + s, s + 1))))
        .bind(|x| State(Box::new(move |s: i32| (x * s, s))));
    
    let (result, final_state) = state_computation.run(10);
    println!("State Monad结果: {}, 最终状态: {}", result, final_state);
    
    // 实际应用示例
    functional_pipeline_example();
}

fn functional_pipeline_example() {
    println!("\n=== 函数式管道 ===");
    
    // 数据处理管道
    let data = vec![1, 2, 3, 4, 5];
    
    let processed: Vec<String> = data
        .into_iter()
        .map(|x| x * 2)                    // 倍增
        .filter(|&x| x > 5)                // 过滤
        .map(|x| x.to_string())            // 转换为字符串
        .collect();
    
    println!("处理后的数据: {:?}", processed);
    
    // 使用fold进行复杂计算
    let numbers = vec![1, 2, 3, 4, 5];
    let result = numbers
        .iter()
        .fold((0, 0), |(sum, count), &x| (sum + x, count + 1));
    
    let (sum, count) = result;
    let average = if count > 0 { sum as f64 / count as f64 } else { 0.0 };
    println!("总和: {}, 平均值: {:.2}", sum, average);
}

37.2 透镜(Lenses)和棱镜(Prisms)

rust 复制代码
// 透镜:不可变数据访问和修改
trait Lens<S, A> {
    fn get(&self, source: &S) -> A;
    fn set(&self, source: S, value: A) -> S;
    
    fn modify<F>(&self, source: S, f: F) -> S
    where
        F: FnOnce(A) -> A,
    {
        let value = self.get(&source);
        self.set(source, f(value))
    }
}

// 自动派生透镜的宏
macro_rules! derive_lens {
    ($struct_name:ident { $($field:ident: $field_type:ty),* $(,)? }) => {
        impl $struct_name {
            $(
                pub fn $field() -> impl Lens<$struct_name, $field_type> {
                    struct FieldLens;
                    
                    impl Lens<$struct_name, $field_type> for FieldLens {
                        fn get(&self, source: &$struct_name) -> $field_type {
                            source.$field.clone()
                        }
                        
                        fn set(&self, mut source: $struct_name, value: $field_type) -> $struct_name {
                            source.$field = value;
                            source
                        }
                    }
                    
                    FieldLens
                }
            )*
        }
    };
}

// 用户结构体
#[derive(Debug, Clone)]
struct User {
    id: u64,
    name: String,
    email: String,
    address: Address,
}

#[derive(Debug, Clone)]
struct Address {
    street: String,
    city: String,
    zip_code: String,
}

derive_lens!(User {
    id: u64,
    name: String,
    email: String,
    address: Address
});

derive_lens!(Address {
    street: String,
    city: String,
    zip_code: String
});

// 透镜组合
struct ComposeLens<L1, L2> {
    lens1: L1,
    lens2: L2,
}

impl<S, A, B, L1, L2> Lens<S, B> for ComposeLens<L1, L2>
where
    L1: Lens<S, A>,
    L2: Lens<A, B>,
{
    fn get(&self, source: &S) -> B {
        let intermediate = self.lens1.get(source);
        self.lens2.get(&intermediate)
    }
    
    fn set(&self, source: S, value: B) -> S {
        let intermediate = self.lens1.get(&source);
        let updated_intermediate = self.lens2.set(intermediate, value);
        self.lens1.set(source, updated_intermediate)
    }
}

// 棱镜:处理可选数据
trait Prism<S, A> {
    fn preview(&self, source: &S) -> Option<A>;
    fn review(&self, value: A) -> S;
}

fn main() {
    println!("=== 透镜和棱镜 ===");
    
    let user = User {
        id: 1,
        name: "Alice".to_string(),
        email: "alice@example.com".to_string(),
        address: Address {
            street: "123 Main St".to_string(),
            city: "Techville".to_string(),
            zip_code: "12345".to_string(),
        },
    };
    
    // 使用透镜访问字段
    let name_lens = User::name();
    println!("用户名: {}", name_lens.get(&user));
    
    // 使用透镜修改字段
    let updated_user = name_lens.set(user, "Alicia".to_string());
    println!("更新后的用户: {:?}", updated_user);
    
    // 透镜组合:访问嵌套字段
    let user_city_lens = ComposeLens {
        lens1: User::address(),
        lens2: Address::city(),
    };
    
    let city = user_city_lens.get(&updated_user);
    println!("用户城市: {}", city);
    
    // 修改嵌套字段
    let user_with_new_city = user_city_lens.set(updated_user, "New City".to_string());
    println!("更新城市后的用户: {:?}", user_with_new_city);
    
    // 函数式数据转换
    functional_transformations();
}

fn functional_transformations() {
    println!("\n=== 函数式数据转换 ===");
    
    #[derive(Debug, Clone)]
    struct Person {
        first_name: String,
        last_name: String,
        age: u32,
    }
    
    derive_lens!(Person {
        first_name: String,
        last_name: String,
        age: u32
    });
    
    let people = vec![
        Person {
            first_name: "John".to_string(),
            last_name: "Doe".to_string(),
            age: 30,
        },
        Person {
            first_name: "Jane".to_string(),
            last_name: "Smith".to_string(),
            age: 25,
        },
    ];
    
    // 使用透镜批量修改数据
    let updated_people: Vec<Person> = people
        .into_iter()
        .map(|person| {
            Person::age().modify(person, |age| age + 1)
        })
        .collect();
    
    println!("年龄增加后的人们: {:?}", updated_people);
    
    // 复杂转换:组合多个透镜
    let full_name_lens = ComposeLens {
        lens1: Person::first_name(),
        lens2: Person::last_name(),
    };
    
    // 注意:这个示例需要调整,因为组合透镜的类型需要匹配
    // 实际应用中需要更复杂的透镜组合实现
}

第三十八章:高级模式匹配

38.1 解构和模式守卫

rust 复制代码
#[derive(Debug)]
enum Message {
    Text(String),
    Number(i32),
    Coordinate { x: i32, y: i32 },
    Color(u8, u8, u8),
    Empty,
}

// 复杂模式匹配
fn process_message(msg: Message) -> String {
    match msg {
        // 解构元组变体
        Message::Color(r, g, b) if r == 255 && g == 255 && b == 255 => {
            "纯白色".to_string()
        }
        Message::Color(r, g, b) if r == g && g == b => {
            format!("灰度色: {}", r)
        }
        Message::Color(r, g, b) => {
            format!("RGB({}, {}, {})", r, g, b)
        }
        
        // 解构结构体变体
        Message::Coordinate { x, y } if x == 0 && y == 0 => {
            "原点".to_string()
        }
        Message::Coordinate { x, y } if x.abs() == y.abs() => {
            "在45度线上".to_string()
        }
        Message::Coordinate { x, y } => {
            format!("坐标({}, {})", x, y)
        }
        
        // 绑定子模式
        Message::Text(ref s) if s.len() > 50 => {
            "长文本".to_string()
        }
        Message::Text(s) => {
            format!("文本: {}", s)
        }
        
        Message::Number(n @ 0..=100) => {
            format!("小数字: {}", n)
        }
        Message::Number(n) => {
            format!("大数字: {}", n)
        }
        
        Message::Empty => {
            "空消息".to_string()
        }
    }
}

// @ 模式绑定
fn process_complex_data(data: &(Option<i32>, Result<String, &str>)) -> String {
    match data {
        (Some(n @ 1..=10), Ok(ref s)) if s.len() < 5 => {
            format!("小数字 {} 和短字符串 {}", n, s)
        }
        (Some(n), Ok(s)) => {
            format!("数字 {} 和字符串 {}", n, s)
        }
        (None, Ok(s)) => {
            format!("无数字,但有字符串: {}", s)
        }
        (Some(n), Err(e)) => {
            format!("数字 {} 和错误: {}", n, e)
        }
        (None, Err(e)) => {
            format!("只有错误: {}", e)
        }
    }
}

// 穷尽性检查的实用模式
fn handle_option(opt: Option<i32>) -> String {
    match opt {
        Some(x) if x > 0 => format!("正数: {}", x),
        Some(0) => "零".to_string(),
        Some(x) => format!("负数: {}", x),
        None => "无值".to_string(),
    }
}

fn main() {
    println!("=== 高级模式匹配 ===");
    
    let messages = vec![
        Message::Text("这是一个短文本".to_string()),
        Message::Text("这是一个非常长的文本,它包含了很多字符,应该被识别为长文本".to_string()),
        Message::Number(42),
        Message::Number(150),
        Message::Coordinate { x: 0, y: 0 },
        Message::Coordinate { x: 5, y: 5 },
        Message::Coordinate { x: 3, y: 7 },
        Message::Color(255, 255, 255),
        Message::Color(128, 128, 128),
        Message::Color(255, 0, 0),
        Message::Empty,
    ];
    
    for msg in messages {
        let result = process_message(msg);
        println!("{}", result);
    }
    
    // @ 模式示例
    let test_data = vec![
        (Some(5), Ok("hi".to_string())),
        (Some(15), Ok("hello".to_string())),
        (None, Ok("test".to_string())),
        (Some(8), Err("错误发生")),
        (None, Err("严重错误")),
    ];
    
    for data in test_data {
        let result = process_complex_data(&data);
        println!("{}", result);
    }
    
    // 穷尽性模式示例
    let options = vec![Some(10), Some(0), Some(-5), None];
    for opt in options {
        println!("{}", handle_option(opt));
    }
}

38.2 模式匹配的编译时优化

rust 复制代码
// 使用match的编译时优化特性
#[derive(Debug, Clone, Copy)]
enum Status {
    Success,
    Failure,
    Pending,
}

impl Status {
    // 这个方法在编译时会被优化
    fn is_terminal(self) -> bool {
        matches!(self, Status::Success | Status::Failure)
    }
    
    fn to_str(self) -> &'static str {
        match self {
            Status::Success => "成功",
            Status::Failure => "失败", 
            Status::Pending => "进行中",
        }
    }
}

// 使用const fn进行编译时计算
#[derive(Debug, PartialEq, Eq)]
enum HttpStatus {
    Ok = 200,
    NotFound = 404,
    ServerError = 500,
}

impl HttpStatus {
    const fn from_code(code: u16) -> Option<Self> {
        match code {
            200 => Some(HttpStatus::Ok),
            404 => Some(HttpStatus::NotFound),
            500 => Some(HttpStatus::ServerError),
            _ => None,
        }
    }
    
    const fn is_success(self) -> bool {
        matches!(self, HttpStatus::Ok)
    }
}

// 模式匹配在常量上下文中的使用
const SUCCESS_STATUS: Status = Status::Success;
const IS_TERMINAL: bool = SUCCESS_STATUS.is_terminal();
const HTTP_OK: Option<HttpStatus> = HttpStatus::from_code(200);

// 智能编译器优化示例
fn process_status(status: Status) -> &'static str {
    // 这个match在编译时会被优化为直接返回
    match status {
        Status::Success => "操作成功完成",
        Status::Failure => "操作失败",
        Status::Pending => "操作仍在进行中",
    }
}

// 使用if let和while let的模式
fn advanced_control_flow() {
    println!("\n=== 高级控制流 ===");
    
    let mut stack = Vec::new();
    stack.push(1);
    stack.push(2);
    stack.push(3);
    
    // while let 模式
    while let Some(top) = stack.pop() {
        println!("弹出: {}", top);
    }
    
    // if let 链 (Rust 1.53+)
    let complex_data = (Some(42), Some("hello"));
    
    if let (Some(n), Some(s)) = complex_data {
        println!("数字: {}, 字符串: {}", n, s);
    }
    
    // 模式匹配与迭代器结合
    let pairs = vec![(1, "one"), (2, "two"), (3, "three")];
    
    for (num, word) in pairs {
        println!("{}: {}", num, word);
    }
    
    // 使用filter_map进行模式匹配过滤
    let mixed_data = vec![Some(1), None, Some(3), None, Some(5)];
    
    let numbers: Vec<i32> = mixed_data
        .into_iter()
        .filter_map(|x| x)
        .collect();
    
    println!("过滤后的数字: {:?}", numbers);
}

fn main() {
    println!("=== 模式匹配优化 ===");
    
    // 常量匹配示例
    println!("常量状态: {:?}", SUCCESS_STATUS);
    println!("是否终止: {}", IS_TERMINAL);
    println!("HTTP状态: {:?}", HTTP_OK);
    
    // 运行时匹配
    let status = Status::Pending;
    println!("状态描述: {}", process_status(status));
    println!("状态字符串: {}", status.to_str());
    println!("是否终止: {}", status.is_terminal());
    
    // HTTP状态处理
    if let Some(http_status) = HttpStatus::from_code(404) {
        println!("HTTP状态: {:?}", http_status);
        println!("是否成功: {}", http_status.is_success());
    }
    
    advanced_control_flow();
    
    // 性能对比演示
    performance_comparison();
}

fn performance_comparison() {
    println!("\n=== 性能对比 ===");
    
    // 编译时优化 vs 运行时计算
    const COMPILE_TIME_RESULT: bool = HttpStatus::Ok.is_success();
    let runtime_result = HttpStatus::Ok.is_success();
    
    println!("编译时结果: {}", COMPILE_TIME_RESULT);
    println!("运行时结果: {}", runtime_result);
    
    // 模式匹配的性能优势
    let values = vec![1, 2, 3, 4, 5];
    
    // 使用模式匹配的迭代器方法
    let sum: i32 = values
        .iter()
        .map(|&x| match x {
            1 => 10,
            2 => 20,
            3 => 30,
            4 => 40,
            5 => 50,
            _ => 0,
        })
        .sum();
    
    println!("模式匹配求和: {}", sum);
}

总结

本章深入探索了Rust的高级类型系统和函数式编程模式:

  1. 高级类型特性:关联类型、GATs、HRTB等
  2. 零成本抽象:编译时多态、类型级编程
  3. 函数式模式:Monad、Functor、透镜、棱镜
  4. 高级模式匹配:解构、模式守卫、编译时优化

这些高级特性让Rust能够在保持零成本抽象的同时,提供强大的表达能力和类型安全性。通过合理运用这些模式,你可以编写出既安全又高效的Rust代码。

继续深入探索Rust的类型系统魔法!🎩


版权声明:本教程仅供学习使用,转载请注明出处。

相关推荐
深耕AI4 小时前
【时钟周期 vs 指令】为什么51单片机需要12个时钟周期?
单片机·嵌入式硬件·51单片机
清风6666668 小时前
基于单片机的多功能智能婴儿车设计
单片机·嵌入式硬件·毕业设计·课程设计·期末大作业
码咔吧咔8 小时前
STM32芯片简介,以及STM32的存储器映射是什么?
stm32·单片机·嵌入式硬件
古城小栈8 小时前
Rust 泛型 敲黑板
rust
古城小栈8 小时前
Rust Trait 敲黑板
开发语言·rust
别掩10 小时前
MOS防倒灌电路设计
单片机·嵌入式硬件
夜流冰10 小时前
EE - 电容电感电路中电流的变化
单片机·嵌入式硬件
橙露11 小时前
STM32中断配置全解析:从寄存器到HAL库的实战应用
stm32·单片机·嵌入式硬件
idcardwang12 小时前
esp32s3-pwm介绍与stm32的不同原理
单片机·嵌入式硬件
码咔吧咔12 小时前
Flash 是什么?SRAM 是什么?它们的作用、特点、区别、在 STM32 中如何使用?
stm32·嵌入式硬件