rust学习-模式

介绍

模式由如下一些内容组合而成
(1)字面量
(2)解构的数组、枚举、结构体或者元组
(3)变量
(4)通配符
(5)占位符

match 分支

match VALUE {
    PATTERN => EXPRESSION,
    PATTERN => EXPRESSION,
    PATTERN => EXPRESSION,
}

match 表达式必须是 穷尽(exhaustive)
模式 _ 可以匹配所有情况,不过它从不绑定任何变量,忽略任何未指定值的情况很有用

if let 条件表达式

if let 表达式的缺点:
其穷尽性没有为编译器所检查,match 表达式则检查了。
如果去掉最后 else 块而遗漏处理一些情况,编译器也不会警告这类错误

fn main() {
    let favorite_color: Option<&str> = None;
    let is_tuesday = false;
    let age: Result<u8, _> = "34".parse();

	// 从 favorite_color 中读不出Some,因为它是None
    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");
    }
}

while let 条件循环

fn main() {
	let mut stack = Vec::new();

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

	// 只要模式匹配就一直进行 while 循环
	// 一旦其返回 None,while 循环停止
	while let Some(top) = stack.pop() {
		println!("{}", top);
	}
}

// 3
// 2
// 1

for 循环

fn main() {
	let v = vec!['a', 'b', 'c'];

	// 使用 for 循环来解构,或拆开一个元组作为 for 循环的一部分
	// 使用 enumerate 方法适配一个迭代器来产生一个值和其在迭代器中的索引
	for (index, value) in v.iter().enumerate() {
		println!("{} is at index {}", value, index);
	}
}

// a is at index 0
// b is at index 1
// c is at index 2

let 语句

let x = 5;
let (x, y, z) = (1, 2, 3); // 将一个元组与模式匹配

// 错误情况
// let (x, y) = (1, 2, 3);

如果希望忽略元组中一个或多个值,也可以使用 _ 或 …

函数参数

在参数中解构元组

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

fn main() {
    let point = (3, 5);
    // 值 &(3, 5) 会匹配模式 &(x, y)
    print_coordinates(&point); // Current location: (3, 5)
}

也可以在闭包参数列表中使用模式

Refutability(可反驳性): 模式是否会匹配失效

能匹配任何传递的可能值的模式被称为是 不可反驳的(irrefutable)
let x = 5; 语句中的 x
x 可以匹配任何值所以不可能会失败

对某些可能的值进行匹配会失败的模式被称为是 可反驳的(refutable)。
if let Some(x) = a_value 表达式中的 Some(x)
如果变量 a_value 中的值是 None 而不是 Some,
那么 Some(x) 模式不能匹配。

函数参数、 let 语句和 for 循环只能接受不可反驳的模式
if let 和 while let 表达式被限制为只能接受可反驳的模式

可反驳的正例

if let Some(x) = some_option_value {
    println!("{}", x);
}

不可反驳的反例

if let x = 5 {
    println!("{}", x);
};

match 匹配分支必须使用可反驳模式,
除了最后一个分支需要使用能匹配任何剩余值的不可反驳模式

匹配字面量

fn main(){
	let x = 1;

	match x {
		1 => println!("one"), // 打印1
		2 => println!("two"),
		3 => println!("three"),
		_ => println!("anything"),
	}
}

匹配命令变量

fn main() {
    let x = Some(5);
    let y = 10;

    match x {
        Some(50) => println!("Got 50"),
        Some(y) => println!("Matched, y = {:?}", y), // x最终匹配的是这一行,其中y=5
        // Some(a) => println!("Matched, a = {:?}", a), 如果前一行换成这个,打印为a=5
        _ => println!("Default case, x = {:?}", x),
    }

    println!("at the end: x = {:?}, y = {:?}", x, y); // x = Some(5), y = 10
}

或条件匹配

fn main() {
	let x = 1;

	match x {
		1 | 2 => println!("one or two"), // 打印当前行
		3 => println!("three"),
		_ => println!("anything"),
	}
}

范围匹配

范围只允许用于数字或 char 值,因为编译器会在编译时检查范围不为空。
char 和 数字值是 Rust 仅有的可以判断范围是否为空的类型。

fn main() {
	let x = 5;

	match x {
		// ..= 语法允许你匹配一个闭区间范围内的值
		// 相比 1..=5,使用 | 则不得不指定 1 | 2 | 3 | 4 | 5,相反指定范围就简短的多
		1..=5 => println!("one through five"), // 打印当前行
		_ => println!("something else"),
	}
}
fn main() {
	let x = 'c';

	match x {
		'a'..='j' => println!("early ASCII letter"), // 打印该行
		'k'..='z' => println!("late ASCII letter"),
		_ => println!("something else"),
	}
}

解构结构体

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

fn main() {
    let p = Point { x: 0, y: 7 };
    
	// 创建变量a和b来解构x和y
    let Point { x: a, y: b } = p;
    assert_eq!(0, a);
    assert_eq!(7, b);
    
    let p1 = Point { x: 0, y: 7 };
     // 简写
    let Point { x, y } = p1;
    assert_eq!(0, x);
    assert_eq!(7, y);
}

使用字面量作为结构体模式的一部分进行解构

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

fn main() {
    let p = Point { x: 0, y: 7 };

    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),
    }
}

解构枚举

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

fn main() {
    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
            )
        }
    }
}

解构嵌套的结构体和枚举

enum Color {
   Rgb(i32, i32, i32),
   Hsv(i32, i32, i32),
}

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

fn main() {
    let msg = Message::ChangeColor(Color::Hsv(0, 160, 255));

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

// 打印结果
// Change the color to hue 0, saturation 160, and value 255

解构结构体和元组

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

fn main() {
    let ((feet, inches), Point {x, y}) = ((3, 10), Point { x: 3, y: -10 });
	println!("feet = {}", feet);
	println!("inches = {}", inches);

	println!("x = {}", x);
	println!("y = {}", y);
}

// feet = 3
// inches = 10
// x = 3
// y = -10

使用 _ 忽略整个值

使用下划线(_)作为匹配但不绑定任何值的通配符模式

//  在函数签名中使用 _
fn foo(_: i32, y: i32) {
    println!("This code only uses the y parameter: {}", y);
}

fn main() {
    foo(3, 4);
}

使用嵌套的 _ 忽略部分值

fn main() {
	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);
}
fn main() {
	let numbers = (2, 4, 8, 16, 32);

	match numbers {
		(first, _, third, _, fifth) => {
			println!("Some numbers: {}, {}, {}", first, third, fifth)
		},
	}
}

单独使用下划线不会绑定值

fn main() {
	let s = Some(String::from("Hello!"));

	// s的所有权没有被移动给_
	if let Some(_) = s {
		println!("found a string");
	}

	// 打印正常
	println!("{:?}", s);
}

用 … 忽略剩余值

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

fn main() {
	let origin = Point { x: 0, y: 0, z: 0 };
	match origin {
		// 通过使用 .. 来忽略 Point 中除 x 以外的字段
		Point { x, .. } => println!("x is {}", x),
	}

    let numbers = (2, 4, 8, 16, 32);
    match numbers {
    	// 只匹配元组中的第一个和最后一个值并忽略掉所有其它值
        (first, .., last) => {
            println!("Some numbers: {}, {}", first, last);
        },
    }
}

异常情况

fn main() {
    let numbers = (2, 4, 8, 16, 32);

    match numbers {
    	// 不知道首尾审略多少个元素,报错
        (.., second, ..) => {
            println!("Some numbers: {}", second)
        },
    }
}

匹配守卫match guard

一个指定于 match 分支模式之后的额外 if 条件,它也必须被满足才能选择此分支

fn main() {
	let num = Some(4);

	match num {
		// 第一个条件满足后,不会执行第二个条件
		Some(x) if x < 5 => println!("less than five: {}", x),
		Some(x) => println!("{}", x),
		None => (),
	}
}

使用守卫测试和外部变量的相等性

fn main() {
    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);
}

// Default case, x = Some(5)
// at the end: x = Some(5), y = 10
fn main() {
	let x = 4;
	let y = false;

	match x {
		4 | 5 | 6 if y => println!("yes"), // x 是 4|5|6时,且 y= true 才执行
		_ => println!("no"),
	}
}

@ 绑定

enum Message {
    Hello { id: i32 },
}

fn main() {
	let msg = Message::Hello { id: 5 };

	match msg {
		// 捕获了任何匹配此范围的值,并同时测试其值是否匹配这个范围模式
		Message::Hello { id: id_variable @ 3..=7 } => {
			println!("Found an id in range: {}", id_variable)
		},
		Message::Hello { id: 10..=12 } => {
			println!("Found an id in another range")
		},
		Message::Hello { id } => {
			println!("Found some other id: {}", id)
		},
	}
}

// Found an id in range: 5
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值