"首次提交"

This commit is contained in:
2024-06-08 15:01:12 +08:00
parent 6e0f708d0a
commit 84349a2469
112 changed files with 3272 additions and 0 deletions

1
p18.match/match_learn/.gitignore vendored Executable file
View File

@ -0,0 +1 @@
/target

View File

@ -0,0 +1,8 @@
[package]
name = "match_learn"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

107
p18.match/match_learn/src/main.rs Executable file
View File

@ -0,0 +1,107 @@
use std::{env::var, sync::atomic::AtomicI32, vec};
fn main() {
println!("Hello, world!");
learn();
}
struct Point {
x: i32,
y: i32,
}
fn learn() {
let var = 3;
match var {
//@绑定val使用..匹配一些值
val @ 1..=4 => println!("match 1..4, {}", val),
_ => println!("match"),
}
let mut var = vec![1, 2, 3, 4, 5, 6, 7];
while let Some(var) = var.pop() {
match var {
//@绑定val使用|来进行多重匹配
val @ (1 | 3 | 5) => println!("match 1,3,5 => {}", val),
_ => println!("miss match val {}", var),
}
}
let mut var = vec![1, 2, 3, 4, 5, 6, 7];
let cond = 2;
while let Some(var) = var.pop() {
match var {
//使用if语句来进行进一步的限制b不满足条件的同样会走到其他分支
val @ (1 | 3 | 5) if val > cond => println!("match 1,3,5 > {} => {}", cond, val),
val @ (1 | 3 | 5) => println!("match 1,3,5 <= {} => {}", cond, val),
_ => println!("aa miss match val {}", var),
}
}
let var = vec!["first", "second", "third", "fourth", "last"];
match var[..] {
[last, .., end] => println!("start str is {}, end str is {}", last, end),
_ => {}
}
let var = ("first", "second", "third", "fourth", "last");
// let var = ("first", "second", "third", "fourth", "end");
match var {
(last, .., "last") => println!("a str end by \"last\", start str is {}", last),
_ => println!("not match a tuple end with \"last\""),
}
//let var = (12, "string");
let var = (123, "string");
match var {
(x, y) if x == 12 => {
println!("fist is 12, second is {}", y);
}
(x, y) => {
println!("fist is not 12 but {}, second is {}", x, y);
}
}
//解构元组
let var = (123, "string");
let (x, y) = var;
println!("after x:{}, y{}", x, y);
//解构结构体
let var = Point { x: 23, y: 34 };
let Point { x, y } = var; //解构时成员明明必须相同
println!("after x:{}, y{}", x, y);
//区间匹配
let c = 'c';
match c {
'a'..='z' => {
println!("is a lower char");
}
'A'..='Z' => {
println!("is a upper char");
}
'0'..='9' => {
println!("is a number");
}
_ => {
println!("other char");
}
}
let var = Point { x: 23, y: 34 };
deconstruct((23, 34), ((45, 23423), var));
//可以通过元组将结构体和元组嵌套进行解构
//使用_开头的变量即使未使用也不会导致编译器警告。
let var = Point { x: 23, y: 34 };
let ((_w, _z), Point { x, y }) = ((12, 34), var);
//_不会绑定变量转移所有权所以再使用_后所有权还是在原变量上
let var = Some(String::from("strzzzz"));
if let Some(_) = var {
println!("find a string");
}
println!("str is {:?}", var);
}
fn deconstruct((h, t): (i32, i32), ((w, r), Point { x, y }): ((i32, i32), Point)) {
println!("h:{},t:{}, w:{},r:{},x:{},y:{},", h, t, w, r, x, y);
}