init code

This commit is contained in:
nap.liu
2023-12-08 19:41:26 +08:00
commit d1b95f1096
98 changed files with 2890 additions and 0 deletions

View File

@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "structures"
version = "0.1.0"

View File

@@ -0,0 +1,8 @@
[package]
name = "structures"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,117 @@
// 禁用未使用的代码警告
#![allow(dead_code)]
#[derive(Debug)]
struct Person {
name: String,
age: u8,
}
// 单位结构 类似 单位元组(Unit Tuple)
// 虽然和单位元组类似,但是每一个 struct 都是独一无二的。
struct Unit;
// 元组结构
struct Pair(i32, f32);
// 两个字段的结构
#[derive(Debug)]
struct Point {
x: f32,
y: f32,
}
// 结构体可以嵌套使用
#[derive(Debug)]
struct Rectangle {
// 长方形可以使用 top、left 和 bottom、right 两个点来表示
top_left: Point,
bottom_right: Point,
}
impl Rectangle {
fn rect_area(&self) -> f64 {
// 解构两个坐标点
let Rectangle {
top_left,
bottom_right,
} = self;
// 计算宽高
let width = bottom_right.x - top_left.x;
let height = bottom_right.y - top_left.y;
// 计算面积
width as f64 * height as f64
}
fn square(top_left: &Point, size: f32) -> Rectangle {
Rectangle {
// 复制 Point 结构体
top_left: Point { ..*top_left },
// 按照尺寸对左上角的坐标进行扩大
bottom_right: Point {
x: top_left.x + size,
y: top_left.y + size,
},
}
}
}
fn main() {
let name = String::from("Peter");
let age = 27;
// 如果变量和结构体的字段名正好相同,则可以省略字段名
let peter = Person { name, age };
// 使用 fmt::Debug 来打印结构体
println!("{:?}", peter);
// 实例化 `Point` 结构体
let point: Point = Point { x: 10.3, y: 0.4 };
// 通过字段访问结构体
println!("point coordinates: ({}, {})", point.x, point.y);
// 使用一个已经存在的结构体的内容来补充剩余的字段,创建一个新的结构体。
let bottom_right = Point { x: 5.2, ..point };
// `bottom_right.y` will be the same as `point.y` because we used that field
// from `point`
// `bottom_right.y` 和 `point.y` 的值相同,
// 因为 `button_right.y` 的值是从 `point` 上复制过来的
println!("second point: ({}, {})", bottom_right.x, bottom_right.y);
// `let` 也可以对结构体进行结构赋值
let Point {
x: left_edge,
y: top_edge,
} = point;
let _rectangle = Rectangle {
// 实例化结构体也是一个表达式,该表达式返回新的结构体实例
top_left: Point {
x: left_edge,
y: top_edge,
},
bottom_right: bottom_right,
};
// 实例化一个 `Unit` 结构
let _unit = Unit;
// 实例化一个 元组结构体
let pair = Pair(1, 0.1);
// 访问元组结构体和元组本身的访问行为相同
println!("pair contains {:?} and {:?}", pair.0, pair.1);
// 解构元组结构体同样和解构元组相同
let Pair(integer, decimal) = pair;
println!("pair contains {:?} and {:?}", integer, decimal);
let square = Rectangle::square(&point, 100f32);
println!("square: \n{:#?}", square);
println!("square area: {}", square.rect_area());
}

7
3.Custom Types/3.2 Eumns/Cargo.lock generated Normal file
View File

@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "enums"
version = "0.1.0"

View File

@@ -0,0 +1,8 @@
[package]
name = "enums"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,73 @@
fn example01() {
// 使用枚举类型对web事件进行分类。
// 枚举的每一项都是独一无二的,枚举的每一项都可以包含任意数据
// 但是枚举的每一项都属于该枚举类型
// `PageLoad != PageUnload` 和 `KeyPress(char) != Paste(String)` 都是成立的
enum WebEvent {
// 枚举的每一项都是一个独立的
PageLoad,
PageUnload,
// 使用类似元组结构来保存数据
KeyPress(char),
Paste(String),
// 或者使用结构体保存数据
Click { x: i64, y: i64 },
}
// 该函数接收 `WebEvent` 枚举,也就是说可以接受该枚举下定义的任意一项数据
fn inspect(event: WebEvent) {
match event {
WebEvent::PageLoad => println!("page loaded"),
WebEvent::PageUnload => println!("page unloaded"),
// Destructure `c` from inside the `enum` variant.
WebEvent::KeyPress(c) => println!("pressed '{}'.", c),
WebEvent::Paste(s) => println!("pasted \"{}\".", s),
// Destructure `Click` into `x` and `y`.
WebEvent::Click { x, y } => {
println!("clicked at x={}, y={}.", x, y);
}
}
}
let pressed = WebEvent::KeyPress('x');
// `to_owned()` 通过克隆 `&str` 引用的数据 创建一新的 `String` 类型
let pasted = WebEvent::Paste("my text".to_owned());
let click = WebEvent::Click { x: 20, y: 80 };
let load = WebEvent::PageLoad;
let unload = WebEvent::PageUnload;
inspect(pressed);
inspect(pasted);
inspect(click);
inspect(load);
inspect(unload);
}
fn example02() {
enum VeryVerboseEnumOfThingsToDoWithNumbers {
Add,
Subtract,
}
impl VeryVerboseEnumOfThingsToDoWithNumbers {
fn run(&self, x: i32, y: i32) -> i32 {
match self {
// 这里的 Self 就是一个类型别名,等于当前 impl 的类型
Self::Add => x + y,
Self::Subtract => x - y,
}
}
}
// 创建一个类型别名,类型别名并没有定义新的类型,只是用作缩短类型声明
type Operations = VeryVerboseEnumOfThingsToDoWithNumbers;
// 类型别名可以有效的缩短类型声明
let x = Operations::Add;
}
fn main() {
example01();
example02();
}

7
3.Custom Types/3.2.1 use/Cargo.lock generated Normal file
View File

@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "uses"
version = "0.1.0"

View File

@@ -0,0 +1,8 @@
[package]
name = "uses"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,38 @@
// 禁用未使用的代码警告
#![allow(dead_code)]
enum Status {
Rich,
Poor,
}
enum Work {
Civilian,
Soldier,
}
fn main() {
// crate 关键字等于当前的根作用域。
// 使用 `use` 关键字把指定类型引用到当前作用域,
// 这样每次使用导入的类型的时候就不需要明确指定完整的路径了
use crate::Status::{Poor, Rich};
// 可以使用通配符 `*` 把对应作用域下的所有导出内容都导入到当前作用域下。
use crate::Work::*;
// 等于 Status::Poor
let status = Poor;
// 等于 Work::Civilian
let work = Civilian;
match status {
// 因为前面明确的使用 `use` 关键字把 `Status` 导入到了当前作用域,所以这里不需要写 `Status::`
Rich => println!("The rich have lots of money!"),
Poor => println!("The poor have no money..."),
}
match work {
// 同上
Civilian => println!("Civilians work!"),
Soldier => println!("Soldiers fight!"),
}
}

7
3.Custom Types/3.2.2 C-like/Cargo.lock generated Normal file
View File

@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "c-like"
version = "0.1.0"

View File

@@ -0,0 +1,8 @@
[package]
name = "c-like"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,25 @@
// 禁用未使用的代码警告
#![allow(dead_code)]
// 当不指明任意类型的时候,枚举项默认从 0 开始
enum Number {
Zero,
One,
Two,
}
// 明确指明枚举项的值
enum Color {
Red = 0xff0000,
Green = 0x00ff00,
Blue = 0x0000ff,
}
fn main() {
// 枚举可以强制转换成数字
println!("zero is {}", Number::Zero as i32);
println!("one is {}", Number::One as i32);
println!("roses are #{:06x}", Color::Red as i32);
println!("violets are #{:06x}", Color::Blue as i32);
}

View File

@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "testcase_linked_list"
version = "0.1.0"

View File

@@ -0,0 +1,8 @@
[package]
name = "testcase_linked_list"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,61 @@
// 把 List 枚举定义的所有项都导入到全局
use crate::List::*;
enum List {
// Cons 定义为元组类型,第一个位是值,第二位是下一个值的指针
Cons(u32, Box<List>),
// Nil 表示链表结束 没有下一项了
Nil,
}
impl List {
fn new() -> List {
Nil
}
fn prepend(self, elem: u32) -> List {
// 生成一个新的 Cons 把当前的链表放到新的 Cons 中
Cons(elem, Box::new(self))
}
// 计算链表长度
fn len(&self) -> usize {
// 因为 Rust 会自动进行解引用操作 所以这里可以直接使用 self 而不是使用 *self
match self {
// 递归计算所有链表节点
Cons(_, next) => 1 + next.len(),
// 末尾节点没有值直接返回 0
Nil => 0,
}
}
// 格式化链表成字符串
fn stringify(&self) -> String {
// *号解引用会转移变量所有权,但是因为参数上声明是个引用
// 所以这里会报错,不能把值从引用中转移出来
// 解决方案就是在声明语句前加上 ref 关键字来表示变量是引用形式使用的
match *self {
// 这里使用 ref 关键字来声明变量是一个引用,而不是转移变量的所有权
// head 不需要添加 ref 关键字使用为 head 是一个 i32 的基础值,直接保存在栈上
// 而 Box<List> 的值是保存在堆上的。
Cons(head, ref tail) => {
format!("{}, {}", head, tail.stringify())
}
Nil => format!("Nil"),
}
}
}
fn main() {
// 创建一个空链表
let mut list = List::new();
// 从前面开始添加一些节点
list = list.prepend(1);
list = list.prepend(2);
list = list.prepend(3);
// 查看链表的状态
println!("linked list has length: {}", list.len());
println!("{}", list.stringify());
}

7
3.Custom Types/3.3 constants/Cargo.lock generated Normal file
View File

@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "constants"
version = "0.1.0"

View File

@@ -0,0 +1,8 @@
[package]
name = "constants"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,21 @@
// 全局定义常量
static LANGUAGE: &str = "Rust"; // 可以被修改的常量,修改常量是不安全的
const THRESHOLD: i32 = 10; // 不能修改的常量
fn is_big(n: i32) -> bool {
// 全局的常量可以在任意位置访问
n > THRESHOLD
}
fn main() {
let n = 16;
// 在主线程访问常量
println!("This is {}", LANGUAGE);
println!("The threshold is {}", THRESHOLD);
println!("{} is {}", n, if is_big(n) { "big" } else { "small" });
// 报错! 不能修改常量的值
THRESHOLD = 5;
// FIXME ^ 注释掉这行代码
}