rust 个例

fn main() {
let a = [4,3,2,1];

// 通过索引和值的方式迭代数组 `a`
for (i,v) in a.iter().enumerate() {
println!("第{}个元素是{}",i+1,v);
}
}

================================================================

fn main() {
let names = [String::from("liming"),String::from("hanmeimei")];
for _name in &names {
// do something with name...
}

println!("{:?}", names);

let numbers = [1, 2, 3];
// numbers中的元素实现了 Copy,因此无需转移所有权
for _n in numbers {
// do something with name...
}

println!("{:?}", numbers);
}

=========================================================

fn main() {
    let alphabets = ['a', 'E', 'Z', '0', 'x', '9' , 'Y'];

    // fill the blank with `matches!` to make the code work
    for ab in alphabets {
        assert!(matches!(ab, 'a'..='z' | 'A'..='Z' | '0'..='9'))
    }
} 

 ==========================================================

 

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

fn main() {
// 填空,让 p 匹配第二个分支
let p = Point { x: 1000, y: 1000 };

match p {
Point { x, y: 0 } => println!("On the x axis at {}", x),
// 第二个分支
Point { x: 0..=5, y: y@ (10 | 20 | 30) } => println!("On the y axis at {}", y),
Point { x, y } => println!("On neither axis: ({}, {})", x, y),
}
}

 

===========================================

@ 操作符可以让我们将一个与模式相匹配的值绑定到新的变量上

enum Message {
Hello { id: i32 },
}

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

match msg {
Message::Hello {
id: id@( 3..=7),
} => println!("id 值的范围在 [3, 7] 之间: {}", id),
Message::Hello { id: newid@(10 | 11 | 12) } => {
println!("id 值的范围在 [10, 12] 之间: {}", newid);
}
Message::Hello { id } => println!("Found some other id: {}", id),
}
}

 

 

=============================================

使用 .. 忽略一部分值

fn main() {
let numbers = (2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048);

match numbers {
(first,..,last) => {
assert_eq!(first, 2);
assert_eq!(last, 2048);
}
}
}

 

=============================================

使用模式 &mut V 去匹配一个可变引用时,你需要格外小心,因为匹配出来的 V 是一个值,而不是可变引用

fn main() {
let mut v = String::from("hello,");
let r = &mut v;

match r {
_value => _value.push_str(" world!")
}
}

posted @   CrossPython  阅读(64)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
点击右上角即可分享
微信分享提示