乱读天书, 不求甚解
周祎骏的个人云笔记
Toggle navigation
乱读天书, 不求甚解
主页
Linux:系统配置
Linux:用户管理
Linux:优化排错
Linux:进程调度
Linux:文件系统
Linux:网络
Linux:系统服务
Linux:安全
Linux:内核
容器:Docker
容器:containerd
容器编排:Kubernetes
IAC:Terraform
大数据:Hadoop
大数据:Zookeeper
大数据:Hbase
消息队列:rsyslog
消息队列:kafka
数据库:MySQL
数据库:MongoDB
搜索引擎:Elasticsearch
时序数据库:OpenTSDB
网站服务:Nginx
编程:Bash
编程:Perl
编程:Python
编程:C
编程:JAVA
编程:Rust
版本控制:gitlab
知识管理:docusaurus
常用小工具
关于我
标签
Rust 02.01 控制流运算符match
2023-02-05 10:10:59
36
0
0
admin
> match # 例子 ```rust fn match_n_1(n:i32){ match n{ 1 => { println!("It is 1");} 2 => { println!("It is 2");} 3|4 => { println!("It is 3 or 4");} 5 ..= 9 => { println!("It is 5 to 9");} _ => { println!("others");} //匹配剩余所有 } } fn main() { match_n_1(7); } ``` ```rust struct Point {x:i32,y:i32,} fn main() { match (Point{x:1,y:0}) { Point{x,y:0} => println!("y=0 and x = {}",x), //匹配y=0 的,抓取x Point{x,..} => println!("x = {}",x), //无视其它参数,只抓取x } } ``` **match 必须穷举所有的可能** *** # 语法糖if let match 有一个语法糖if let ,以下两段代码效果相同 ```rust match value { some_value => xxx, _ => (), } if let some_value = value { xxx } ``` if let 与if 的区别是: if 后面必须是布尔值,if let 可以判断各种类型。 # match抓取内容 ```rust fn main() { let n = Some(2); match n{ Some(1) => { println!("It is 1");} Some(x) => { println!("It is some({})",x);} // 抓取数值,赋值给x _ => { println!("others");} } } ``` ```rust fn main() { let n = 100; match n{ the_n@ 1 ..= 1000 => { println!("It is {}",the_n);} _ => { println!("others");} } } ``` # match使用匹配守卫添加额外条件 ```rust fn main() { let y = 5; let n = Some(2); match n { Some(x) if x < y => println!("x < {} and x = {}",y,x), Some(x) => println!("x = {}",x), _ => println!("Others"), } } ```
上一篇:
Rust 02.00 控制流
下一篇:
Rust 03.00 函数
文档导航