提交 032a345e 编写于 作者: 梦境迷离's avatar 梦境迷离

add rust oop

上级 1fc0bd70
......@@ -27,9 +27,11 @@ use point_function::*;
use simple_array_data_type::*;
use smart_point::*;
use struct_data_type::*;
use thread_syntax::*;
use variables_function::*;
pub mod panic_function;
pub mod thread_syntax;
pub mod generic_traits_lifetimes;
pub mod iterator_demonstration;
pub mod struct_data_type;
......@@ -109,5 +111,21 @@ fn main() {
println!("====================");
box_function();
println!("====================");
example_guessing_game();
create_thread();
println!("====================");
join_thread();
println!("====================");
use_var_thread();
println!("====================");
channel_thread();
println!("====================");
send_multi_msg();
println!("====================");
copy_tx();
println!("====================");
mutex_thread();
println!("====================");
mutex_multi_thread();
println!("====================");
//example_guessing_game();
}
use std::sync::{Arc, mpsc, Mutex};
use std::thread;
use std::time::Duration;
pub fn create_thread() {
///新线程将在主线程结束时停止,无论它是否已完成运行
thread::spawn(|| {
for i in 1..10 {
println!("hi number {} from the spawned thread!", i);
thread::sleep(Duration::from_millis(1));
}
});
for i in 1..5 {
println!("hi number {} from the main thread!", i);
thread::sleep(Duration::from_millis(1));//短暂停止,最终仍取决于操作系统如何调度线程。
}
}
pub fn join_thread() {
//返回值保存在变量handle中
let handle = thread::spawn(|| {
for i in 1..10 {
println!("hi number {} from the spawned thread!", i);
thread::sleep(Duration::from_millis(1));
}
});
//handle.join().unwrap(); //阻塞当前线程,先执行thread::spawn,再执行main(main中for在后面)
for i in 1..5 {
println!("hi number {} from the main thread!", i);
thread::sleep(Duration::from_millis(1));
}
///阻塞当前正在运行的线程,直到由该句柄表示的线程终止
handle.join().unwrap();//即thread::spawn先执行,main后执行
}
pub fn use_var_thread() {
///尝试在另一个线程中使用由主线程创建的向量
let v = vec![1, 2, 3];
let handle = thread::spawn(move || {//必须在闭包前加move,强制获取v变量的所有权而不是借用这个值
println!("Here's a vector: {:?}", v);
});
//v不能再被主线程使用,所有权已经转移
handle.join().unwrap();
}
pub fn channel_thread() {
///发送器和接收器
let (tx, rx) = mpsc::channel();
//产生的线程需要拥有通道的发送端才能通过通道发送消息。
thread::spawn(move || {
//tx移动到新线程,并开始发送val值
let val = String::from("hi");
//在此之后val被移到tx,无法再次使用
tx.send(val).unwrap();
});
//使用rx接收器接收消息
let received = rx.recv().unwrap();//try_recv方法不会阻塞
println!("Got: {}", received);
}
pub fn send_multi_msg() {
///使用channel间隔着发送多个消息
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("thread"),
];
for val in vals {
tx.send(val).unwrap();
thread::sleep(Duration::from_secs(1));
}
});
///使用rx接收,将rx视为迭代器
for received in rx {
println!("Got: {}", received);
}
}
pub fn copy_tx() {
let (tx, rx) = mpsc::channel();
///克隆一个发送器
let tx1 = mpsc::Sender::clone(&tx);
thread::spawn(move || {
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("thread"),
];
for val in vals {
tx1.send(val).unwrap();
thread::sleep(Duration::from_secs(1));
}
});
thread::spawn(move || {
let vals = vec![
String::from("more"),
String::from("messages"),
String::from("for"),
String::from("you"),
];
for val in vals {
tx.send(val).unwrap();
thread::sleep(Duration::from_secs(1));
}
});
for received in rx {
println!("Got: {}", received);
}
}
pub fn mutex_thread() {
let m = Mutex::new(5);
{
let mut num = m.lock().unwrap();
*num = 6;
}
println!("m = {:?}", m);
}
pub fn mutex_multi_thread() {
///Arc是原子的,Rc不是
let counter = Arc::new(Mutex::new(0));
//Mutex Arc 均实现了send sync两个接口,这两个接口都是标记接口(特质)
//实现send特质可以在线程间转移同一变量的所有权
//实现sync特质可以允许多个线程访问同一变量
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());
}
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "rust-oop"
version = "0.1.0"
[package]
name = "rust-oop"
version = "0.1.0"
authors = ["梦境迷离 <dreamylost@outlook.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
/// RUST OOP
pub mod gui {
pub struct AveragedCollection {
list: Vec<i32>,
average: f64,
}
impl AveragedCollection {
pub fn add(&mut self, value: i32) {
self.list.push(value);
self.update_average();
}
pub fn remove(&mut self) -> Option<i32> {
let result = self.list.pop();
match result {
Some(value) => {
self.update_average();
Some(value)
}
None => None,
}
}
pub fn average(&self) -> f64 {
self.average
}
fn update_average(&mut self) {
let total: i32 = self.list.iter().sum();
self.average = total as f64 / self.list.len() as f64;
}
}
//Button,Image,和SelectBox,将从继承Component并且因此继承draw方法。
//他们每个人都可以重写该draw方法来定义其自定义行为
//rust没有继承,需要使用其他方法实现这一功能
pub trait Draw {
fn draw(&self);
}
//使用Screen<T: Draw>将限制为一个Screen实例,该实例具有一个全部为Button类型或全部TextField类型的组件的列表。
//如果您只拥有同类集合,则最好使用泛型和特质范围,因为定义会在编译时被单一化以使用具体类型。
pub struct Screen {
pub components: Vec<Box<dyn Draw>>,//Box<dyn Draw> 实现了Draw特质的任何类型组件
}
impl Screen {
pub fn run(&self) {
for component in self.components.iter() {
component.draw();
}
}
}
///实现特质
pub struct Button {
pub width: u32,
pub height: u32,
pub label: String,
}
impl Draw for Button {
fn draw(&self) {
//自定义实现
}
}
pub struct SelectBox {
pub width: u32,
pub height: u32,
pub options: Vec<String>,
}
impl Draw for SelectBox {
fn draw(&self) {
//自定义实现
}
}
}
//安全的特质对象
//返回类型不是Self。
//没有通用类型参数。
use crate::lib::gui::{Button, Screen, SelectBox};
use crate::oop_blog::blog;
use crate::rust_blog::blog_rust;
pub mod lib;
pub mod oop_blog;
pub mod rust_blog;
fn main() {
let screen = Screen {
components: vec![
Box::new(SelectBox {
width: 75,
height: 10,
options: vec![
String::from("Yes"),
String::from("Maybe"),
String::from("No")
],
}),
Box::new(Button {
width: 50,
height: 10,
label: String::from("OK"),
}),
],
};
screen.run();
blog();
blog_rust();
}
\ No newline at end of file
use crate::oop_blog::blog_lib::Post;
pub fn blog() {
let mut post = Post::new();
post.add_text("I ate a salad for lunch today");
assert_eq!("", post.content());
post.request_review();
assert_eq!("", post.content());
post.approve();
assert_eq!("I ate a salad for lunch today", post.content());
}
///使用状态模式(状态耦合)
//通过完全按照面向对象语言所定义的方式来实现状态模式,我们无法充分利用Rust的优势
pub mod blog_lib {
//1.定义结构体描述博客
pub struct Post {
//使用特质对象类型定义state
state: Option<Box<dyn State>>,
//内容
content: String,
}
//2.实现博客
impl Post {
//定义博客的统一构造方法
pub fn new() -> Post {
Post {
state: Some(Box::new(Draft {})),
content: String::new(),
}
}
//存储内容的方法
pub fn add_text(&mut self, text: &str) {
self.content.push_str(text);
}
//委托给State的content方法
pub fn content(&self) -> &str {
self.state.as_ref().unwrap().content(self)
}
//请求查看内容
pub fn request_review(&mut self) {
if let Some(s) = self.state.take() {
self.state = Some(s.request_review())
}
}
pub fn approve(&mut self) {
if let Some(s) = self.state.take() {
self.state = Some(s.approve())
}
}
}
//3.博客状态
trait State {
//该方法仅在持有该类型的Box上调用时才有效
fn request_review(self: Box<Self>) -> Box<dyn State>;
//审批博客文章
fn approve(self: Box<Self>) -> Box<dyn State>;
fn content<'a>(&self, post: &'a Post) -> &'a str {
""
}
}
struct Draft {}
//4.实现State特质的状态 Draft(草稿状态)
impl State for Draft {
fn request_review(self: Box<Self>) -> Box<dyn State> {
Box::new(PendingReview {})
}
fn approve(self: Box<Self>) -> Box<dyn State> {
self
}
}
//5.实现State特质的状态 PendingReview (审查状态)
struct PendingReview {}
impl State for PendingReview {
fn request_review(self: Box<Self>) -> Box<dyn State> {
self
}
fn approve(self: Box<Self>) -> Box<dyn State> {
Box::new(Published {})
}
}
//6.实现State特质的状态 Published (已发表状态)
struct Published {}
impl State for Published {
fn request_review(self: Box<Self>) -> Box<dyn State> {
self
}
fn approve(self: Box<Self>) -> Box<dyn State> {
self
}
fn content<'a>(&self, post: &'a Post) -> &'a str {
&post.content
}
}
}
\ No newline at end of file
use crate::rust_blog::blog_lib::Post;
///面向对象模式并非总是Rust中最好的解决方案。
pub fn blog_rust() {
let mut post = Post::new();
post.add_text("I ate a salad for lunch today");
let post = post.request_review();
let post = post.approve();
assert_eq!("I ate a salad for lunch today", post.content());
}
pub mod blog_lib {
//不使用状态,使每个状态与博客成为一个实体
pub struct Post {
content: String,
}
pub struct DraftPost {
content: String,
}
impl Post {
pub fn new() -> DraftPost {
DraftPost {
content: String::new(),
}
}
pub fn content(&self) -> &str {
&self.content
}
}
impl DraftPost {
pub fn add_text(&mut self, text: &str) {
self.content.push_str(text);
}
pub fn request_review(self) -> PendingReviewPost {
PendingReviewPost {
content: self.content,
}
}
}
pub struct PendingReviewPost {
content: String,
}
impl PendingReviewPost {
pub fn approve(self) -> Post {
Post {
content: self.content,
}
}
}
}
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册