前言

这里只是简单列出Rsut语言的知识点


一、基础语法

1.1 变量与可变性

1
2
3
4
let x = 5;          // 不可变绑定
let mut y = 10; // 可变绑定
y = 15; // 允许修改
const MAX: u32 = 100; // 常量

1.2 数据类型

类型 说明 示例
标量类型 单个值 i32, f64, bool, char
复合类型 多个值 tuple, array
自定义类型 用户定义 struct, enum
1
2
3
4
5
6
7
// 元组
let tup: (i32, f64, u8) = (500, 6.4, 1);
let (x, y, z) = tup; // 解构

// 数组
let a = [1, 2, 3, 4, 5];
let first = a[0]; // 1

二、控制流

2.1 条件语句

1
2
3
4
5
6
7
8
9
10
11
12
13
let number = 6;

if number % 4 == 0 {
println!("divisible by 4");
} else if number % 2 == 0 {
println!("divisible by 2");
} else {
println!("not divisible by 4 or 2");
}

// if表达式
let condition = true;
let num = if condition { 5 } else { 6 };

2.2 循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// loop循环
let mut count = 0;
loop {
count += 1;
if count == 3 {
break;
}
}

// while循环
let mut num = 3;
while num != 0 {
println!("{num}!");
num -= 1;
}

// for循环
let a = [10, 20, 30, 40, 50];
for element in a {
println!("the value is: {element}");
}

三、函数

3.1 函数定义

1
2
3
4
5
6
7
8
fn add(x: i32, y: i32) -> i32 {
x + y // 隐式返回(无分号)
}

fn main() {
let sum = add(5, 3);
println!("Sum: {sum}");
}

3.2 闭包

1
2
3
4
5
6
7
let add_one = |x| x + 1;
println!("5 + 1 = {}", add_one(5));

// 捕获环境
let y = 10;
let add_y = |x| x + y;
println!("5 + 10 = {}", add_y(5));

四、所有权系统(Rust核心特性)

4.1 所有权规则

  1. Rust中每个值都有一个所有者
  2. 一次只能有一个所有者
  3. 当所有者离开作用域,值将被丢弃

4.2 移动语义

1
2
3
let s1 = String::from("hello");
let s2 = s1; // s1的所有权移动到s2
// println!("{s1}"); // 错误!s1不再有效

4.3 克隆

1
2
3
let s1 = String::from("hello");
let s2 = s1.clone(); // 深拷贝
println!("s1 = {s1}, s2 = {s2}"); // 都有效

4.4 借用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let s = String::from("hello");

// 不可变引用
let len = calculate_length(&s);

// 可变引用
let mut s = String::from("hello");
change(&mut s);

fn calculate_length(s: &String) -> usize {
s.len()
}

fn change(some_string: &mut String) {
some_string.push_str(", world");
}

4.5 生命周期

1
2
3
4
5
6
7
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}

五、结构体与枚举

5.1 结构体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}

let user1 = User {
email: String::from("user@example.com"),
username: String::from("someusername123"),
active: true,
sign_in_count: 1,
};

// 方法
impl User {
fn display(&self) {
println!("User: {}", self.username);
}
}

5.2 枚举

1
2
3
4
5
6
7
8
9
10
11
enum IpAddr {
V4(u8, u8, u8, u8),
V6(String),
}

let home = IpAddr::V4(127, 0, 0, 1);
let loopback = IpAddr::V6(String::from("::1"));

// Option枚举
let some_number = Some(5);
let absent_number: Option<i32> = None;

六、模式匹配

6.1 match表达式

1
2
3
4
5
6
7
8
9
10
let coin = Coin::Quarter(UsState::Alaska);
let value = match coin {
Coin::Penny => 1,
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter(state) => {
println!("State quarter from {:?}!", state);
25
},
};

6.2 if let语法糖

1
2
3
4
5
6
let some_value = Some(3);

// 等价于 match some_value { Some(3) => ..., _ => () }
if let Some(3) = some_value {
println!("three");
}

七、错误处理

7.1 panic! 宏

1
2
3
fn main() {
panic!("crash and burn");
}

7.2 Result 枚举

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
use std::fs::File;

let f = File::open("hello.txt");

let f = match f {
Ok(file) => file,
Err(error) => panic!("Problem opening the file: {:?}", error),
};

// ?运算符
fn read_username() -> Result<String, io::Error> {
let mut s = String::new();
File::open("hello.txt")?.read_to_string(&mut s)?;
Ok(s)
}

八、泛型与Trait

8.1 泛型

1
2
3
4
5
6
7
8
9
10
11
12
13
struct Point<T> {
x: T,
y: T,
}

impl<T> Point<T> {
fn x(&self) -> &T {
&self.x
}
}

let integer = Point { x: 5, y: 10 };
let float = Point { x: 1.0, y: 4.0 };

8.2 Trait

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
pub trait Summary {
fn summarize(&self) -> String;
}

pub struct NewsArticle {
pub headline: String,
pub location: String,
pub author: String,
pub content: String,
}

impl Summary for NewsArticle {
fn summarize(&self) -> String {
format!("{}, by {} ({})", self.headline, self.author, self.location)
}
}

九、智能指针

9.1 Box

1
2
let b = Box::new(5);
println!("b = {}", b); // 5

9.2 Rc(引用计数)

1
2
3
4
use std::rc::Rc;

let a = Rc::new(5);
let b = Rc::clone(&a);

9.3 RefCell(内部可变性)

1
2
3
4
5
use std::cell::RefCell;

let cell = RefCell::new(5);
*cell.borrow_mut() = 10;
println!("{}", *cell.borrow()); // 10

十、并发编程

10.1 线程

1
2
3
4
5
6
7
8
9
10
11
12
13
use std::thread;

let handle = thread::spawn(|| {
for i in 1..10 {
println!("hi number {i} from the spawned thread!");
}
});

for i in 1..5 {
println!("hi number {i} from the main thread!");
}

handle.join().unwrap();

10.2 通道

1
2
3
4
5
6
7
8
9
10
11
use std::sync::mpsc;

let (tx, rx) = mpsc::channel();

thread::spawn(move || {
let val = String::from("hi");
tx.send(val).unwrap();
});

let received = rx.recv().unwrap();
println!("Got: {}", received);

10.3 Mutex

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
use std::sync::{Arc, Mutex};

let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];

for _ in 0..10 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}

for handle in handles {
handle.join().unwrap();
}

println!("Result: {}", *counter.lock().unwrap());

十一、常用集合

11.1 Vector

1
2
3
4
5
6
7
8
9
10
let mut v: Vec<i32> = Vec::new();
v.push(1);
v.push(2);

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

for i in &mut v {
*i += 50;
}

11.2 String

1
2
3
4
let mut s = String::from("foo");
s.push_str("bar");
let s2 = "baz".to_string();
let s3 = s + &s2; // s的所有权被移动

11.3 HashMap

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

let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);

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

十二、模块系统

12.1 模块定义

1
2
3
4
5
6
7
8
9
10
11
mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {}
}
}

pub use crate::front_of_house::hosting;

pub fn eat_at_restaurant() {
hosting::add_to_waitlist();
}

12.2 文件结构

1
2
3
4
5
restaurant
├── Cargo.toml
└── src
├── lib.rs
└── front_of_house.rs

十三、Cargo与包管理

13.1 Cargo.toml

1
2
3
4
5
6
7
[package]
name = "my_project"
version = "0.1.0"
edition = "2021"

[dependencies]
rand = "0.8.5"

13.2 常用命令

1
2
3
4
5
cargo new my_project   # 创建新项目
cargo build # 编译项目
cargo run # 编译并运行
cargo test # 运行测试
cargo doc --open # 生成并打开文档

十四、最佳实践

  1. 所有权优先:理解并合理使用所有权系统
  2. 错误处理:优先使用Result而非panic!
  3. 类型安全:充分利用Rust的类型系统
  4. 并发安全:使用Arc/Mutex等安全并发原语
  5. 零成本抽象:合理使用泛型和trait
  6. 测试驱动:编写单元测试和集成测试
  7. 文档注释:使用///编写文档注释
  8. 模式匹配:充分利用match和if let
  9. 避免unsafe:只在必要时使用unsafe代码
  10. 性能优化:理解Rust的内存模型进行优化

Rust是一种系统编程语言,专注于安全、并发和性能。它通过所有权系统在编译期保证内存安全,无需垃圾回收。Rust适合系统编程、WebAssembly、嵌入式系统和高性能服务端应用等场景。