code_snippets
match
- 基本匹配
- 匹配范围
- 匹配元组
- 匹配结构体
- 匹配枚举
enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(i32, i32, i32), } fn main() { let msg = Message::Move { x: 10, y: 20 }; match msg { Message::Quit => println!("The Quit variant has no data to destructure."), Message::Move { x, y } => println!("Move in the x direction {} and in the y direction {}", x, y), Message::Write(text) => println!("Text message: {}", text), Message::ChangeColor(r, g, b) => println!("Change the color to red {}, green {}, and blue {}", r, g, b), } }
- 匹配引用
- 匹配守卫
- 匹配集合
for
-
用于迭代器循环(for-in-loops): 跟在in 后边的如果是集合,会自动转型为迭代器 【语法糖?没找到对应的文档】
for 用于迭代器循环,例如 for i in 0..5。 这种循环是 Rust 中常见的一种语法糖,用于遍历任何实现了 IntoIterator trait 的集合,直到迭代器返回 None 或循环体中使用 break 为止。 用于实现 trait(impl Trait for Type):
-
for 用于实现 trait,例如 impl Trait for Type。
这种用法表示为一个类型实现某个 trait。 用于高阶 trait 边界(higher-ranked trait bounds):
-
for 用于高阶 trait 边界,例如 for<'a> &'a T: PartialEq
。 这种用法表示对生命周期参数的高阶约束。
闭包
基本语法 |args| { body } args 是闭包的参数列表。 body 是闭包的函数体。 示例 1. 捕获环境变量
fn main() {
let x = 42;
let closure = |y: i32| x + y;
println!("Result: {}", closure(10)); // 输出: Result: 52
}
-
捕获可变变量
在这个示例中,闭包 closure 捕获了可变变量 x,并且不需要显式声明捕获方式。编译器会自动推断出 x 是以可变借用的方式捕获的。 -
使用 move 关键字
在这个示例中,闭包 closure 捕获了变量 x 的所有权。使用 move 关键字显式地声明了所有权转移。
map and set
使用 HashMap
HashMap 是一个键值对的集合,其中每个键都是唯一的。
创建 HashMap
use std::collections::HashMap;
fn main() {
// 创建一个空的 HashMap
let mut map: HashMap<String, i32> = HashMap::new();
// 插入键值对
map.insert(String::from("apple"), 1);
map.insert(String::from("banana"), 2);
map.insert(String::from("cherry"), 3);
// 访问元素
let apple_count = map.get("apple");
match apple_count {
Some(&count) => println!("Apple count: {}", count),
None => println!("No apple found"),
}
// 遍历 HashMap
for (fruit, count) in &map {
println!("{}: {}", fruit, count);
}
}
修改 HashMap
use std::collections::HashMap;
fn main() {
let mut map: HashMap<String, i32> = HashMap::new();
map.insert(String::from("apple"), 1);
map.insert(String::from("banana"), 2);
// 更新值
let apple_count = map.entry(String::from("apple")).or_insert(0);
*apple_count += 1;
println!("{:?}", map);
}
使用 HashSet
HashSet 是一个存储唯一值的集合。
创建 HashSet
use std::collections::HashSet;
fn main() {
// 创建一个空的 HashSet
let mut set: HashSet<i32> = HashSet::new();
// 插入元素
set.insert(1);
set.insert(2);
set.insert(3);
// 检查元素是否存在
if set.contains(&1) {
println!("Set contains 1");
}
// 遍历 HashSet
for &num in &set {
println!("{}", num);
}
}