文章目录

一、迭代器

关于更多详情查看​​【标准库】​

fn main() {
// iter - 在每次迭代中借用集合中的一个元素
let names = vec!["zhangsan", "lisi","wangwu","zhaoliu"];
for name in names.iter(){
match name{
&"zhangsan" => println!("The people is zhangsan"),
_ => println!("Hello:{}",name),
}
}


//into_iter - 获取遍历元素所有权,会消耗集合
let names_2 = vec!["zhangsan", "lisi","wangwu","zhaoliu"];
for name in names_2.into_iter(){
match name {
"zhangsan" => println!("The people is zhangsan"),
_ => println!("Hello:{}",name),
}
}


//iter_mut - 可变地(mutably)借用集合中的每个元素,从而允许集合被就地修改。
let mut names_3 = vec!["zhangsan", "lisi","wangwu","zhaoliu"];
for name in names_3.iter_mut(){
*name = match name {
&mut "zhangsan" => "The people is zhangsan",
_ => "other people",
}
}
println!("names_3:{:?}",names_3);

}

// The people is zhangsan
// Hello:lisi
// Hello:wangwu
// Hello:zhaoliu

// The people is zhangsan
// Hello:lisi
// Hello:wangwu
// Hello:zhaoliu

// names_3:["The people is zhangsan", "other people", "other people", "other people"]
二、match匹配

更好的match详解:​​https://zhuanlan.zhihu.com/p/126369292​​​ 关于更多详情查看​​【标准库】​

fn main() {
let pair = (0,-2);
match pair {
(x, 0) => println!("The first number is {}",x),
(0, y) => println!("The second number is {}",y),
_ => println!("It doesn't match")

}


let number = 13;
match number {
1 => println!("This number is 1"),
2|3|4|5 => println!("This number is 2|3|4|5"),
6...13 => println!("This number is 6..13"), // 范围:[6,13)
13 => println!("13 OK !!!"),
_ => println!("other error"),
}


let tshirt_width = 20;
let tshirt_size = match tshirt_width {
16 => "S", // 16
17 | 18 => "M", // 17 or 18
19...21 => "L", // 19 to 21; 范围:[19,21) 展开=>(19,20)
21..=24 => "xL", // 21 to 24; 范围:[21,24] 展开=>(21,22,23,24)
25 => "XXL",
_ => "Not Available",
};
println!("tshirt_size = {}",tshirt_size);
}

// The second number is -2
// This number is 6..13
// tshirt_size = L

匹配与解构

age()->u8{
15
}

fn main() {
// 引用解构一:
let ref_01 = &12;
match ref_01{
&val =>println!("Got a value is {}",val),
}

// 引用解构二:
match *ref_01{
val =>println!("Got a value is {}",val),
}

// 引用解构三:
let mut ref_02 = 12;
match ref_02{
ref mut val =>{
*val +=12;
println!("修改了变量的值后:{}",val)
}
}

// match 条件匹配
let pair = (2,-12);
match pair {
(x,y) if x == y =>println!(" These are twins !"),
(x,y) if x+y ==-10 =>println!("两个数值相差10!"),
(x,_) if 1 == x%2 =>println!("x是奇数!"),
_ =>println!("No match found!"),
}

match age(){
0 => println!("age error!"),
n@1...13 =>println!("I'm a child of age {:?}",n),
n@13...19=>println!("I'm a teen of age {:?}",n),
n =>println!("I'm an old person of age {:?}",n),
}
}