《Rust权威指南》第18章_模式匹配_草稿

  • 所有可以使用模式的场合
    • match分支
    • if let条件表达式
    • while let条件循环
    • for循环
    • let语句
    • 函数的参数
  • 可失败性:模式是否会匹配失败
  • 模式语法
    • 匹配字面量
    • 匹配命名变量
    • 多重模式
    • 使用…来匹配值区间
    • 使用解构来分解值
      • 解构结构体
      • 解构枚举
      • 解构嵌套的结构体和枚举
      • 解构结构体和元组
    • 忽略模式中的值
      • 使用_忽略整个值
      • 使用嵌套的_忽略值得某些部分
      • 通过以_开头的名称来忽略未使用的变量
      • 使用…忽略值得剩余部分
    • 使用匹配首尾添加额外条件
    • @绑定
fn main() {
    let favorite_color: Option<&str> = None;
    let is_tuesday = false;
    let age: Result<u8, _> = "34".parse();

    if let Some(color) = favorite_color {
        println!("Using your favorite color, {}, as the background", color);
    } else if is_tuesday {
        println!("Tuesday is green day!");
    } else if let Ok(age) = age {
        if age > 30 {
            println!("Using purple as the background color");
        } else {
            println!("Using orange as the background color");
        }
    } else {
        println!("Using blue as the background color");
    }

    let mut stack = Vec::new();

    stack.push(1);
    stack.push(2);
    stack.push(3);

    while let Some(top) = stack.pop() {
        println!("{}", top);
    }

    let v = vec!['a','b','c'];
    for (index, value) in v.iter().enumerate() {
        println!("{} is at index {}", value, index);
    }

    //let模式匹配
    //let PATTEN = EXPRESSION;
    let x = 5;
    let (x, y, z) = (1, 2, 3);

    /*
    let(x, y) = (1, 2, 3);
    错误匹配
    */

    //函数参数模匹配
    let point = (3, 5);
    print_coordinates(&point);

    //可失败模式
    if let x = 5  {
        println!("{}", x);
    }

    //匹配字面量
    let x = 1;
    match x {
        1 => println!("one"),
        2 => println!("two"),
        3 => println!("three"),
        _ => println!("anything"),
    }

    //命名匹配
    let x = Some(5);
    let y = 10;
    match x {
        Some(50) => println!("Got 50"),
        Some(y) => println!("Matched, y = {:?}", y),
        _ => println!("Default case, x = {:?}, y = {:?}", x, y),
    }
    println!("at the end: x = {:?}, y = {:?}", x, y);

    //多重模式
    let x = 1;
    match x {
        1 | 2 => println!("one or two"),
        3 => println!("three"),
        _ => println!("anything"),
    }

    let x = 5;
    match x {
        1...5 => println!("one through five"),
        _ => println!("something else"),
    }

    let x = 'c';
    match x {
        'a'..='j' => println!("early ASCII letter"),
        'k'..='z' => println!("late ASCII letter"),
        _ => println!("something else"),
    }

    //使用解构来分解值
    let p = Point{ x: 0, y: 7 };
    let Point {x: a, y: b } = p;
    assert_eq!(0, a);
    assert_eq!(7, b);

    let p = Point{ x: 0, y: 7 };
    let Point {x, y } = p;
    assert_eq!(0, a);
    assert_eq!(7, b);

    let p = Point{ x: 0, y: 7 };
    let Point{ x, y} = p;
    assert_eq!(0, x);
    assert_eq!(7, y);

    match p {
        Point { x, y: 0 } => println!("On the x axis at {}", x),
        Point { x: 0, y } => println!("On the y axis at {}", y),
        Point { x, y } => println!("On neither axis: ({}, {})", x, y),
    }

    let msg = Message::ChangeColor(0, 160, 255);
    match msg {
        Message::Quit => {
            println!("The Quit variant has no data to destructure.");
        },
        Message::Move { x, y } => {
            println!("Move in the x direction {} and in the y direction {}", x, y);
        },
        Message::Write(text) => println!("Text message: {}", text),
        Message::ChangeColor(r, g, b) => {
            println!(
                "Change the color to red {}, green {}, and blue {}",
                r,
                g,
                b
            )
        }
    }

    let msg = Message_2::ChangeColor(Color::Hsv(0, 160, 255));
    match msg {
        Message_2::ChangeColor(Color::Rgb(r, g, b)) => {
            println!("Change the color to red {}, green {}, and blue {}", r, g, b);
        },
        Message_2::ChangeColor(Color::Hsv(h, s, v)) => {
            println!("Change the color to hue {}, saturation {}, and value {}", h, s, v);
        }
        _ => ()
    }

    let ((feet, inches),Point{x, y}) = ((3, 10), Point{ x: 3, y: -10});

    foo(3, 4);

    let mut setting_value = Some(5);
    let new_setting_value = Some(10);
    match (setting_value, new_setting_value) {
        (Some(_), Some(_)) => {
            println!("Can't overwrite an existing customized value");
        }
        _ => {
            setting_value = new_setting_value;
        }
    }
    println!("setting is {:?}", setting_value);

    let numbers = (2, 4, 8, 16, 32);
    match numbers {
        (first, _, third, _, fifth) => {
            println!("Some numbers: {}, {}, {}", first, third, fifth);
        },
    }

    let _x = 5;
    let y = 10;
    let s = Some(String::from("Hello!"));
    if let Some(_) = s {
        println!("found a string");
    }
    println!("{:?}", s);

    let origin = Point_2 { x: 0, y: 0, z: 0 };
    match origin {
        Point_2{ x, ..} => println!("x is {}", x),
    }

    let numbers = (2, 4, 8, 16, 32);
    match numbers {
        (first, .., last) => {
            println!("Some numbers: {}, {}", first, last);
        },
    }

    let num = Some(4);
    match num {
        Some(x) if x < 5 => println!("less than five: {}", x),
        Some(x) => println!("{}", x),
        None => (),
    }

    let x = Some(5);
    let y = 10;
    match x {
        Some(50) => println!("Got 50"),
        Some(n) if n == y => println!("Matched, n = {:?}", n),
        _ => println!("Default case, x = {:?}", x),
    }
    println!("at the end: x = {:?}, y = {:?}", x, y);

    let x = 4;
    let y = false;
    match x {
        4 | 5 | 6 if y => println!("yes"),
        _ => println!("no"),
    }

    let msg = Message_3::Hello { id: 5 };
    match msg {
        Message_3::Hello { id: id_variable @ 3..=7 } => {
            println!("Found an id in range: {}", id_variable);
        },
        Message_3::Hello { id: 10..=12 } => {
            println!("Found an id in another range");
        },
        Message_3::Hello { id } => {
            println!("Found some other id: {}", id);
        }
    }
}

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

fn foo(_: i32, y: i32) {
    println!("This code only uses the y parameter: {}", y);
}

struct Point {
    x: i32,
    y: i32,
}

struct Point_2 {
    x: i32,
    y: i32,
    z: i32,
}

enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write (String),
    ChangeColor(i32, i32, i32),
}

enum Message_2 {
    Quit,
    Move { x: i32, y: i32 },
    Write (String),
    ChangeColor(Color),
}

enum Message_3 {
    Hello { id: i32 },
}

enum Color {
    Rgb(i32, i32, i32),
    Hsv(i32, i32, i32)
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值