目录
什么是 Rust 集合与字符串
- 集合 (Collections):Rust 标准库提供的数据结构,用于存储多个值,如
Vec
(动态数组)、HashMap
(键值对)和HashSet
(唯一值集合)。 - 字符串 (Strings):Rust 有两种主要字符串类型:
String
(可变、堆分配)和&str
(不可变切片)。
为什么要使用集合与字符串
- 数据管理:集合用于组织和操作一组数据。
- 灵活性:支持动态增长或键值映射。
- 文本处理:字符串处理文本数据,支持 Unicode。
- 性能:选择合适的类型优化内存和速度。
集合类型
Vec<T>
:
- 动态数组,可增长。
- 方法:
push
、pop
、iter
。
HashMap<K, V>
:
- 键值对集合,无序。
- 方法:
insert
、get
、remove
。
HashSet<T>
:
- 唯一值集合,无序。
- 方法:
insert
、contains
。 - 依赖:
HashMap
和HashSet
需use std::collections::{HashMap, HashSet}
。
字符串类型
String
:
- 可变,堆分配,拥有所有权。
- 创建:
String::from("text")
。
&str
:
- 不可变切片,通常是静态字符串或借用。
- 示例:
"hello"
。 - 转换:
&str
到String
:.to_string()
。String
到&str
:&s
。
常用操作
- 集合:
- 添加:
push
(Vec)、insert
(HashMap/Set)。 - 查询:
get
(HashMap)、contains
(HashSet)。 - 迭代:
for
或.iter()
。 - 字符串:
- 拼接:
push_str
(String)、+
(需借用)。 - 切片:
[start..end]
。 - 遍历:
chars()
或bytes()
。
代码示例
Vec 操作
fn main() {
let mut v: Vec<i32> = Vec::new();
v.push(1);
v.push(2);
v.push(3);
for &num in v.iter() {
println!("Num: {}", num);
}
}
运行结果:
Num: 1
Num: 2
Num: 3
HashMap 操作
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert("Alice", 95);
scores.insert("Bob", 87);
if let Some(&score) = scores.get("Alice") {
println!("Alice's score: {}", score);
}
}
运行结果:
Alice's score: 95
字符串操作
fn main() {
let mut s = String::from("Hello");
s.push_str(", Rust!");
let slice = &s[0..5];
println!("Full: {}, Slice: {}", s, slice);
for c in s.chars() {
print!("{}", c);
}
println!();
}
运行结果:
Full: Hello, Rust!, Slice: Hello
Hello, Rust!
参考资料与出站链接
- 官方文档:
- 学习资源:
- 社区支持:
发表回复