rust中的模式匹配是一种结构性匹配,和Javascript的解构赋值有些类似。rust有很多场景都可以使用模式匹配,使用起来简单方便,提高效率。
模式匹配的使用场景
- let声明 let中的模式匹配比较简单,直接上代码:
struct Point {
x: i32,
y: i32,
}
fn main() {
// let声明中的模式匹配
let (a, b) = (0, 1);
println!("a={:?}, b={:?}", a, b);
let Point {x, y} = Point {x:0, y: 1};
println!("x={:?}, y={:?}", x, y);
let [one, two, three] = [1,2,3];
println!("one={:?},two={:?},three={:?}",one, two, three);
}
demo中展示了分别从元组,结构体和数组中使用模式匹配,运行结果如下:
!
- 函数和闭包的参数定义
fn add_str(x: String, ref y: String) -> String {
x + y
}
fn main() {
let sum_str = add_str("hello".to_owned(), " world".to_owned());
assert_eq!("hello world".to_owned(), sum_str)
}
- match表达式
fn print_option_val(op: Option<i32>) {
match op {
Some(val) => println!("The value is {:?}", val),
None => println!("None"),
}
}
fn main() {
print_option_val(Some(1024)); // The value is 1024
print_option_val(None); // None
}
使用match进行模式匹配,可以匹配到Some(1024)的1024到val,当然还有对他类型值表达式可以进行匹配
// 匹配文件读取结果
fn read_toml_match() -> Result<String, std::io::Error> {
let mut f = match File::open("Cargo.tmol") {
Ok(file) => file,
Err(e) => return Err(e)
};
let mut buffer = String::new();
match f.read_to_string(&mut buffer) {
Ok(_) => Ok(buffer),
Err(e) => Err(e)
}
}
// 简化写法, match 部分可以使用“?”简化算是一个语法糖
fn read_toml() -> Result<String, std::io::Error> {
let mut f = File::open("Cargo.toml")?;
let mut buffer = String::new();
f.read_to_string(&mut buffer)?;
Ok(buffer)
}
// 自动解引用
- if let 比较简单的demo
let v = Some("hello world");
if let Some(s) = v {
println!("{}", s);
}
// hello world
- while let
let mut num = Some(0);
while let Some(i) = num {
if i < 10 {
println!("{}", i);
num = Some(i + 1);
} else {
num = None;
println!("b~~~")
}
}
- for
let mut arr = vec![1,2,3,4,5];
for (index, value) in arr.iter().enumerate(){
println!("index = {}, value = {}", index, value);
}
还有很多场景没有涉及,后面再做补充~~~