From f16b3ec86dd82f6015081e1992551c7d33d01891 Mon Sep 17 00:00:00 2001 From: hongyang <1664698982@qq.com> Date: Tue, 16 Apr 2024 22:21:14 +0800 Subject: [PATCH] =?UTF-8?q?=E7=AC=AC=E5=9B=9B=E8=AF=BE=E4=BD=9C=E4=B8=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Readme.md | 182 +++++++++++++++++++++++++++++++------------ src/main.rs | 134 ------------------------------- src/task1/method1.rs | 30 +++++++ src/task1/method2.rs | 43 ++++++++++ src/task2/main.rs | 43 ++++++++++ 5 files changed, 247 insertions(+), 185 deletions(-) delete mode 100644 src/main.rs create mode 100644 src/task1/method1.rs create mode 100644 src/task1/method2.rs create mode 100644 src/task2/main.rs diff --git a/src/Readme.md b/src/Readme.md index 99246bf..a4d0690 100644 --- a/src/Readme.md +++ b/src/Readme.md @@ -1,103 +1,183 @@ ## 笔记一 -元组结构体:所谓元组结构体,也就是元组和结构体的结合体 +泛型 ```rust -struct Color(i32, i32); +fn largest (list: &Vec) -> &T { + let mut largest = &list[0]; -fn main() { - let _black = Color(0, 0); + for item in list { + if *item > *largest { + largest = item; + } + } + + largest } -``` -什么是所有权? +fn main() { + let number_list = vec![32, 50, 25, 100, 65]; + let result = largest(&number_list); + + println!("The largest number is {}", result); -一句话解释:谁(获得着)控制这个数据的生死权利 + let char_list = vec!['y', 'm', 'a', 'q']; -在Rust中,每一个值都有一个决定其生命周期的唯一所有者(owner) + let result = largest(&char_list); -所有权的存在原因? + println!("The largest char is {}", result); +} +``` -- 跟踪代码的哪些部分正在使用heap的哪些数据 -- 最小化heap上的重复数据 -- 清理heap上未使用的数据以免空间不足 ## 笔记二 -`struct`结构体 +结构体由一些字段组成。字段是有类型的,这个类型当然适用于泛型。因此, + +结构体中,是可以出现泛型的。 ```rust -struct User { - active: bool, - username: String, - email: String, - sign_in_count: u32, +struct Point { + x:T, + y:U, } fn main() { - let active = true; - let username = String::from("someusername123"); - let email = String::from("someuser@example123"); - let user1 = User { - active, - username, - email, - sign_in_count: 1, - }; - - let user2 = User { - email: String::from("another@example.com"), - ..user1 - }; + let _both_integer = Point{x:5, y:0}; + let _both_float = Point{x:1.0, y:4.0}; } ``` -`enum`枚举 +## 笔记三 +trait实际是对类型的约束,或者说是代表了一个类(满足条件的)类型。 -`if let` ```rust -fn main() { - let mut optional = Some(0); +trait Animal { + fn myself(self) -> Self; - if let Some(i) = optional { - if i > 9 { - println!("Greater than 9, quit"); - optional = None; + fn eat(&self); + + fn eat_mut(&mut self); +} +``` + + +```rust +use std::fmt::Display; + +struct Pair { + x:T, + y:T, +} + +impl Pair { + fn new(x:T, y:T) ->Self { + Self {x, y} + } +} + +impl Pair { + fn cmp_display(&self) { + if self.x >= self.y { + println!("The largest member is ={}", self.x); } else { - println!("t"); + println!("The largest member is y={}", self.y); } } } + ``` +## 笔记四 + +```rust +pub trait Iterator { + type Item; + + fn next(&mut self) -> Option; +} +``` -`Vec`与HashMap ```rust -fn foo1(s: &str) { +trait Animal { + fn talk(&self); +} + +struct Cat{} +struct Dog{} + +impl Animal for Cat { + fn talk(&self) { + println!("meow"); + } } -fn foo2(s: &[u32]) { +impl Animal for Dog { + fn talk(&self) { + println!("bark"); + } +} +fn animal_talk(a: &T) { + a.talk(); } fn main() { - let s = String::from("aaa"); - foo1(&s); + let d = Dog{}; + let c = Cat{}; - foo1("aaaabbb"); + animal_talk(&d); + animal_talk(&c); +} +``` +## 笔记五 - let v: Vec = vec![1, 2, 3, 4, 5]; - foo2(&v); + ```rust + trait TraitA { + fn do_something(&self); +} - foo2(&[1, 2, 3, 4, 5]); +struct TypeA; + +struct TypeB; + +impl TraitA for TypeA { + fn do_something(&self) { + println!("TypeA is dothing something"); + } } -``` +impl TraitA for TypeB { + fn do_something(&self) { + println!("TypeB is dothing something"); + } +} + +fn main() { + let type_a = TypeA; + + let type_b = TypeB; + + let a: &dyn TraitA = &type_a; + let b: &dyn TraitA = &type_b; + + a.do_something(); + b.do_something(); +} + ``` + +## 笔记六 + +- TypeT 实现了 TraitA 中定义的所有方法。这意味着 TypeT 满足了 TraitA 的所有要求。 + +- 当一个函数接受 &dyn TraitA 类型的参数时, 你可以传入一个 &TypeT 类型的值, 因为 TypeT 实现了 TraitA。 + +- 你可以将 TypeT 作为 TraitA 的具体实现来使用, 也可以将其作为一个实现了 TraitA 的类型来使用。 diff --git a/src/main.rs b/src/main.rs deleted file mode 100644 index 91990a5..0000000 --- a/src/main.rs +++ /dev/null @@ -1,134 +0,0 @@ -// 添加学生 -#[derive(Debug)] -struct Student { - id: u32, - name: String, - age: u32, - grade: u32, - class_id: u32, -} - -#[derive(Debug)] -struct ClassInfo { - id: u32, - name: String, - description: String, -} - -struct StudentManager { - students: Vec, - classes: Vec, -} - -impl StudentManager { - // 创建一个新的StudentManager - fn new() -> Self { - StudentManager { - students: Vec::new(), - classes: Vec::new() - } - } - - // 创建一个新的学生 - fn create_student(&mut self, id: u32, name: &str, age: u32, grade: u32, class_id: u32) { - let student = Student{ - id, - name: name.to_string(), - age, - grade, - class_id, - }; - - self.students.push(student); - } - - // 创建一个新的班级 - fn create_class(&mut self, id: u32, name: &str, description: &str) { - let class_info = ClassInfo{ - id, - name: name.to_string(), - description: description.to_string(), - }; - self.classes.push(class_info); - } - - // 根据id查找学生 - fn get_student(&self, id: u32) -> Option<&Student> { - self.students.iter().find(|s| s.id == id) - } - - // 根据id查找班级 - fn get_class(&self, id: u32) -> Option<&ClassInfo> { - self.classes.iter().find(|c| c.id == id) - } - - // 更新学生信息 - fn update_student(&mut self, id: u32, name: &str, age: u32, grade: u32, class_id: u32) { - if let Some(student) = self.students.iter_mut().find(|s| s.id == id) { - student.name = name.to_string(); - student.age = age; - student.grade = grade; - student.class_id = class_id; - } - } - - // 更新班级信息 - fn update_class(&mut self, id: u32, name: &str, description: &str) { - if let Some(class_info) = self.classes.iter_mut().find(|c| c.id == id) { - class_info.name = name.to_string(); - class_info.description = description.to_string(); - } - } - - // 根据id删除学生 - fn delete_student(&mut self, id: u32) { - self.students.retain(|s| s.id != id); - } - - // 根据id删除班级 - fn delete_class(&mut self, id: u32) { - self.classes.retain(|c| c.id != id); - } -} - -fn main() { - let mut student_manager = StudentManager::new(); - - // 创建班级 - student_manager.create_class(1, "Rust课程" , "Rust学习课程"); - student_manager.create_class(2, "Move课程" , "Move学习课程"); - - // 创建学生 - student_manager.create_student(1, "Lehy", 20, 90, 1); - - student_manager.create_student(2, "Bob", 21, 85, 1); - - student_manager.create_student(3, "Nancy", 20, 92, 2); - - // 查找学生和班级 - // 查找学生和班级 - if let Some(student) = student_manager.get_student(1) { - println!("Found student: {:?}", student); - } - if let Some(class_info) = student_manager.get_class(1) { - println!("Found class: {:?}", class_info); - } - - // 更新学生和班级信息 - student_manager.update_student(2, "Bob Simith", 22, 88, 2); - student_manager.update_class(1, "Rust课程", "Rust课程更新" ); - - println!("更新数据后:"); - // 查找学生和班级 - // 查找学生和班级 - if let Some(student) = student_manager.get_student(2) { - println!("Found student: {:?}", student); - } - if let Some(class_info) = student_manager.get_class(1) { - println!("Found class: {:?}", class_info); - } - - // 删除学生和班级 - student_manager.delete_student(2); - student_manager.delete_class(2); -} \ No newline at end of file diff --git a/src/task1/method1.rs b/src/task1/method1.rs new file mode 100644 index 0000000..76c4c12 --- /dev/null +++ b/src/task1/method1.rs @@ -0,0 +1,30 @@ +// #[derive(Debug)] +// enum MyNumber { +// Int(i32), +// Float(f64), +// String(String), +// } +// +// impl MyNumber { +// fn add(&self, other: &Self) -> Self { +// match (self, other) { +// (MyNumber::Int(a), MyNumber::Int(b)) => MyNumber::Int(a + b), +// (MyNumber::Float(a), MyNumber::Float(b)) => MyNumber::Float(a + b), +// (MyNumber::String(a), MyNumber::String(b)) => MyNumber::String(format!("{}{}", a, b)), +// _ => unimplemented!("Cannot add these types"), +// } +// } +// } +// +// fn main() { +// let numbers = vec![ +// MyNumber::Int(5), +// MyNumber::Float(3.14), +// MyNumber::String(String::from("Hello, ")), +// ]; +// +// for number in numbers { +// let result = number.add(&MyNumber::Int(3)); +// println!("Result: {:?}", result); +// } +// } \ No newline at end of file diff --git a/src/task1/method2.rs b/src/task1/method2.rs new file mode 100644 index 0000000..7a648a7 --- /dev/null +++ b/src/task1/method2.rs @@ -0,0 +1,43 @@ +// #[derive(Debug, Clone, Copy, PartialEq, Eq)] +// struct Point { +// x: i32, +// y: i32, +// } +// +// impl std::ops::Add for Point { +// type Output = Self; +// +// fn add(self, other: Self) -> Self { +// Point { +// x: self.x + other.x, +// y: self.y + other.y, +// } +// } +// } +// +// trait Addable { +// fn add(&self, other: &Self) -> Self; +// } +// +// impl Addable for Point { +// fn add(&self, other: &Self) -> Self { +// Point { +// x: self.x + other.x, +// y: self.y + other.y, +// } +// } +// } +// +// fn main() { +// let p1 = Point { x: 1, y: 2 }; +// let p2 = Point { x: 3, y: 4 }; +// +// // 使用 + 运算符直接相加 +// let p3 = p1 + p2; +// println!("p1 + p2 = {:?}", p3); +// +// // 使用 Trait Object 调用 add 方法 +// let addable: &dyn Addable = &p1; +// let p4 = addable.add(&p2); +// println!("Using Trait Object: {:?}", p4); +// } \ No newline at end of file diff --git a/src/task2/main.rs b/src/task2/main.rs new file mode 100644 index 0000000..348d431 --- /dev/null +++ b/src/task2/main.rs @@ -0,0 +1,43 @@ +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Point { + x: i32, + y: i32, +} + +impl std::ops::Add for Point { + type Output = Self; + + fn add(self, other: Self) -> Self { + Point { + x: self.x + other.x, + y: self.y + other.y, + } + } +} + +trait Addable { + fn add(&self, other: &Self) -> Self; +} + +impl Addable for Point { + fn add(&self, other: &Self) -> Self { + Point { + x: self.x + other.x, + y: self.y + other.y, + } + } +} + +fn main() { + let p1 = Point { x: 1, y: 2 }; + let p2 = Point { x: 3, y: 4 }; + + // 使用 + 运算符直接相加 + let p3 = p1 + p2; + println!("p1 + p2 = {:?}", p3); + + // 使用 Trait Object 调用 add 方法 + let addable: &dyn Addable = &p1; + let p4 = addable.add(&p2); + println!("Using Trait Object: {:?}", p4); +} \ No newline at end of file