学习rust_day06

Vectors

  • 在单一数据结构存储多个值
  • 在内存中连续存储(相邻)
  • 元素必须是同类型
  • Vec来自标准库

例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
fn main() {
let v: Vec<i32> = Vec::new(); //需要手动标注类型

let w = vec![1, 2, 3]; //无需手动标注类型

let mut v = Vec::new();

//向vec中加入元素
v.push(1);
v.push(2);
v.push(3);

//引用vec元素
let third: &i32 = &v[2];

let third: Option<&i32> = v.get(2);
match third {
Some(third) => println!("Get it"),
None => println!("No way"),
}

//遍历vec中的元素
for n_ref in &v {
let n_plus_one: i32 = *n_ref + 1;
println!("{n_plus_one}");
}

//在vec中存储不同的元素
enum S {
Int(i32),
Float(f64),
Text(String)
}

let row = vec![S::Int(3), S::Text(String::from("hello")), S::Float(3.14)];

}

String

Rust中只存在一种字符串类型:str(&str) 字符串切片。

例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
fn main() {
//初始化String
let mut s = String::new();

let data = "wtf";
let s = data.to_string();

let s = "wtf".to_string();

let s = String::from("wtf");

//修改或更新String
let mut s = String::from("foo");
let s2 = "bar";
s.push_str(s2);
println!("{s2}"); //S2仍然可以使用

//连接String
let s1 = String::from("Hello ");
let s2 = String::from("world");
let s3 = s1 + &s2; //s2后续仍然可以使用

let s = format!("{s3}-{s2}-{s2}");

//对String进行切片
let s4 = &s[0..4];

//遍历String
for c in s4.chars() {
println!("{c}"); //输出字符
}

for c in s4.bytes() {
println!("{c}"); //输出数字
}

}

HashMap

  • 存储键值对(K,V)的映射的集合
  • Hashing函数
  • 通过K来查找

例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
use std::collections::HashMap;

fn main() {
//创建HashMap
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Red"), 20);

let vec = vec![("Blue", 10), ("Red", 20)];
let map: HashMap<_, _> = vec.into_iter().collect();

//访问HashMap的值
let team_name = String::from("Blue");
let score = scores.get(&team_name).copied().unwrap_or(0);

//遍历HashMap
for (key, value) in &scores {
println!("{} : {}", key, value);
}

//更新HashMap
scores.insert(String::from("Blue"), 30);
scores.insert(String::from("Blue"), 35);

for (key, value) in &scores {
println!("{} : {}", key, value);
}

scores.entry(String::from("Yellow")).or_insert(10); //如果不存在键才会插入
scores.entry(String::from("Blue")).or_insert(50);

for (key, value) in &scores {
println!("{} : {}", key, value);
}

//基于key原有的值进行更新
let text = "hello world world wonderful world";
let mut map = HashMap::new();
for word in text.split_whitespace() {
let count = map.entry(word).or_insert(0);
*count += 1;
}
println!("{map:#?}");

}

学习rust_day06
https://zlsf-zl.github.io/2026/03/15/学习rust-day06/
作者
ZLSF
发布于
2026年3月15日
许可协议