rust-day2-项目管理-集合-错误处理

rust-7 「rustwiki.org」

第7章:管理大型项目

包和crate的概念:

包是Cargo管理的单位,可以包含一个或多个crate。

Crate是Rust编译的基本单位,分为两种:

  • 二进制crate:生成可执行文件。
  • 库crate:供其他crate依赖和使用。

一个包可以包含多个二进制crate,但通常只有一个库crate。

模块系统:

模块用于在crate内部组织代码,帮助结构化代码并控制可见性。
通过mod关键字定义模块,可以将相关功能分组。

隐私规则:

Rust的隐私规则决定代码的公开(public)或私有(private)状态。
公开项可以通过pub关键字标记,可被其他crate访问;私有项仅在定义它们的crate内可见。

路径和使用:

使用路径(如crate::module::item)来引用模块中的项。
use关键字可以导入路径,简化代码引用。

第8章:常见集合

vector

新建vector

1
let v: Vec<i32> = Vec::new();

push

1
2
3
4
5
6
let mut v = Vec::new();

v.push(5);
v.push(6);
v.push(7);
v.push(8);

索引访问和get访问

1
2
3
4
5
6
7
8
9
10

let v = vec![1, 2, 3, 4, 5];

let third: &i32 = &v[2];
println!("The third element is {}", third);

match v.get(2) {
Some(third) => println!("The third element is {}", third),
None => println!("There is no third element."),
}

通过枚举存储多种类型

1
2
3
4
5
6
7
8
9
10
11
enum SpreadsheetCell {
Int(i32),
Float(f64),
Text(String),
}

let row = vec![
SpreadsheetCell::Int(3),
SpreadsheetCell::Text(String::from("blue")),
SpreadsheetCell::Float(10.12),
];

String

字符串还是很复杂的。不同的语言选择了不同的向开发者展示其复杂性的方式。Rust 选择了以准确的方式处理 String 数据作为所有 Rust 程序的默认行为,这意味着开发者们必须更多的思考如何预先处理 UTF-8 数据。这种权衡取舍相比其他语言更多的暴露出了字符串的复杂性,不过也使你在开发生命周期后期免于处理涉及非 ASCII 字符的错误。

1
2
let mut s = String::from("foo");
s.push_str("bar");

单独字符 push

1
2
let mut s = String::from("lo");
s.push('l');

HashMap

语法

1
2
3
4
5
6
7
8
9
10
11
use std::collections::HashMap;

let mut scores = HashMap::new();

scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);

let team_name = String::from("Blue");
let score = scores.get(&team_name);


遍历

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

根据旧值更新一个值

1
2
3
4
for word in text.split_whitespace() {
let count = map.entry(word).or_insert(0);
*count += 1;
}

第9章:错误处理

Result枚举

Result<T, E>是Rust的核心错误处理类型,表示操作成功(Ok(T))或失败(Err(E))。

1
2
3
4
5
6
7
fn divide(a: i32, b: i32) -> Result<i32, String> {
if b == 0 {
Err("除数不能为0".to_string())
} else {
Ok(a / b)
}
}

错误传播

使用?操作符简化错误传播,自动将Err值返回调用者。

如果divide返回Err,程序会立即返回Err。

1
let result = divide(10, 2)?;

错误处理策略

可以使用match表达式处理Result

1
2
3
4
match result {
Ok(value) => println!("结果: {}", value),
Err(e) => println!("错误: {}", e),
}