├── 错误处理与格式化输出
├── hello2.txt
├── .gitignore
├── hello.txt
├── Cargo.toml
├── Cargo.lock
└── src
│ └── format.rs
├── bytes
├── .gitignore
├── Cargo.toml
├── Cargo.lock
└── src
│ └── main.rs
├── 复合类型
├── .gitignore
├── Cargo.lock
├── Cargo.toml
└── src
│ ├── tuple.rs
│ ├── sort.rs
│ ├── enumeration.rs
│ ├── struct1.rs
│ └── array.rs
├── 宏编程
├── .gitignore
├── Cargo.toml
└── Cargo.lock
├── 并发编程
├── .gitignore
├── examples
│ ├── main5.rs
│ ├── alternate.go
│ ├── alternate1.rs
│ ├── alternate3.rs
│ ├── alternate2.rs
│ ├── barrier.rs
│ └── deadlock.rs
├── Cargo.toml
└── src
│ └── config.rs
├── 异步编程
├── .gitignore
└── Cargo.toml
├── 文件操作
├── src
│ └── hello.txt
├── .gitignore
├── hello.txt
├── lorem_ipsum.txt
├── Cargo.lock
└── Cargo.toml
├── 智能指针
├── .gitignore
├── Cargo.lock
├── Cargo.toml
└── src
│ └── cow.rs
├── 模式匹配
├── .gitignore
├── Cargo.lock
└── Cargo.toml
├── 流程控制
├── .gitignore
├── Cargo.lock
└── Cargo.toml
├── 猜数游戏
├── .gitignore
├── Cargo.toml
├── src
│ └── main.rs
└── Cargo.lock
├── 生命周期
├── .gitignore
├── Cargo.lock
├── Cargo.toml
└── src
│ └── advance.rs
├── minigrep
├── .gitignore
├── Cargo.lock
├── Cargo.toml
├── tests
│ └── search.rs
├── poem.txt
└── src
│ ├── main.rs
│ └── lib.rs
├── rust调用c
├── .gitignore
├── src
│ ├── double.c
│ ├── third.c
│ └── main.rs
├── Cargo.toml
├── Cargo.lock
└── build.rs
├── 基本数据类型
├── .gitignore
├── Cargo.toml
└── Cargo.lock
├── 循环引用与自引用
├── .gitignore
├── Cargo.toml
└── Cargo.lock
├── 所有权和借用
├── .gitignore
├── Cargo.lock
├── Cargo.toml
└── src
│ ├── main.rs
│ └── study.rs
├── 方法_泛型_特征
├── .gitignore
├── Cargo.lock
├── Cargo.toml
└── src
│ ├── inheritance.rs
│ ├── operator_overloading.rs
│ └── polymorphism.rs
├── 构建脚本
├── hello
│ ├── .gitignore
│ ├── Cargo.lock
│ ├── Cargo.toml
│ ├── src
│ │ └── main.rs
│ └── build.rs
├── 条件编译
│ ├── .gitignore
│ ├── src
│ │ └── main.rs
│ ├── Cargo.toml
│ └── build.rs
└── 链接系统库
│ ├── .gitignore
│ ├── Cargo.toml
│ ├── src
│ └── lib.rs
│ ├── Cargo.lock
│ └── build.rs
├── hello_macro
├── .gitignore
├── hello_macro_derive
│ ├── .gitignore
│ ├── Cargo.toml
│ └── src
│ │ └── lib.rs
├── src
│ ├── lib.rs
│ └── main.rs
├── Cargo.toml
└── Cargo.lock
├── linked_list
├── .gitignore
└── Cargo.toml
├── unsafe_rust
├── .gitignore
├── src
│ └── libadd.so
├── Cargo.lock
└── Cargo.toml
├── world_hello
├── .gitignore
├── Cargo.lock
├── Cargo.toml
└── src
│ └── main.rs
├── world_hello2
├── .gitignore
├── Cargo.lock
├── Cargo.toml
└── src
│ └── main.rs
├── 配置文件
├── .gitignore
├── src
│ └── main.rs
├── examples
│ ├── main3.rs
│ ├── main4.rs
│ ├── main5.rs
│ ├── main2.rs
│ └── main1.rs
└── Cargo.toml
├── web服务器
├── 实践多线程_web服务器
│ ├── .gitignore
│ ├── Cargo.lock
│ ├── hello.html
│ ├── 404.html
│ ├── Cargo.toml
│ └── src
│ │ ├── main.rs
│ │ └── lib.rs
├── 异步_web服务器
│ ├── .gitignore
│ ├── hello.html
│ ├── 404.html
│ ├── Cargo.toml
│ └── src
│ │ └── main.rs
├── 异步多线程_web服务器
│ ├── .gitignore
│ ├── hello.html
│ ├── 404.html
│ ├── Cargo.toml
│ └── src
│ │ └── main.rs
└── 单线程版本的_web_服务器
│ ├── .gitignore
│ ├── Cargo.lock
│ ├── Cargo.toml
│ ├── hello.html
│ ├── 404.html
│ └── src
│ └── main.rs
├── 日志与监控
├── .gitignore
├── src
│ └── main.rs
├── Cargo.toml
└── examples
│ ├── main1.rs
│ ├── main3.rs
│ ├── main4.rs
│ └── main5.rs
├── c调用rust
├── .gitignore
├── Cargo.toml
└── src
│ ├── main.c
│ └── lib.rs
├── 实现一个简单的redis
├── mini_redis
│ ├── .gitignore
│ ├── Cargo.lock
│ ├── Cargo.toml
│ └── src
│ │ └── main.rs
├── tokio_hello
│ ├── .gitignore
│ ├── Cargo.toml
│ └── examples
│ │ ├── main2.rs
│ │ ├── main6.rs
│ │ ├── main1.rs
│ │ ├── main3.rs
│ │ ├── main5.rs
│ │ └── main4.rs
├── tokio_select
│ ├── .gitignore
│ └── Cargo.toml
├── tokio_stream
│ ├── .gitignore
│ ├── Cargo.toml
│ └── src
│ │ └── main.rs
├── tokio_tcp
│ ├── .gitignore
│ ├── Cargo.toml
│ └── src
│ │ └── bin
│ │ ├── server.rs
│ │ └── client.rs
├── tokio_优雅的关闭
│ ├── .gitignore
│ ├── Cargo.toml
│ └── src
│ │ └── main.rs
├── tokio_协作式调度
│ ├── .gitignore
│ ├── Cargo.toml
│ ├── examples
│ │ └── example1.rs
│ └── src
│ │ └── main.rs
├── tokio_异步原理
│ ├── .gitignore
│ ├── Cargo.toml
│ └── src
│ │ └── main.rs
├── hello-my-redis
│ ├── .gitignore
│ ├── Cargo.toml
│ ├── examples
│ │ └── hello-redis.rs
│ └── src
│ │ └── main.rs
├── my-redis-stream
│ ├── .gitignore
│ ├── Cargo.toml
│ └── src
│ │ └── bin
│ │ └── client.rs
├── my-redis-共享状态
│ ├── .gitignore
│ ├── Cargo.toml
│ ├── examples
│ │ └── hello-redis.rs
│ └── src
│ │ └── bin
│ │ ├── server.rs
│ │ └── client.rs
└── tokio_异步跟同步共存
│ ├── .gitignore
│ ├── Cargo.toml
│ └── src
│ ├── other.rs
│ └── main.rs
├── sayhello_lib
├── .gitignore
├── Cargo.toml
└── src
│ └── lib.rs
├── study_test
├── .gitignore
├── tests
│ └── add_test.rs
├── Cargo.toml
├── benches
│ └── my_benchmark.rs
└── src
│ └── lib.rs
├── timer_future
├── .gitignore
├── Cargo.toml
└── src
│ └── lib.rs
├── rust_golang_ffi_demo
├── rustdemo
│ ├── .gitignore
│ ├── Cargo.toml
│ └── src
│ │ └── lib.rs
└── golang
│ ├── cgo
│ └── rustdemo.h
│ ├── go.mod
│ ├── mainc
│ └── main.go
├── src
└── main.rs
├── .gitignore
├── README.md
└── Cargo.toml
/错误处理与格式化输出/hello2.txt:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/bytes/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/复合类型/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/宏编程/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/并发编程/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/异步编程/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/文件操作/src/hello.txt:
--------------------------------------------------------------------------------
1 | hello
2 |
--------------------------------------------------------------------------------
/智能指针/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/模式匹配/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/流程控制/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/猜数游戏/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/生命周期/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/minigrep/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/rust调用c/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/基本数据类型/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/循环引用与自引用/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/所有权和借用/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/方法_泛型_特征/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/构建脚本/hello/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/构建脚本/条件编译/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/构建脚本/链接系统库/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/错误处理与格式化输出/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/错误处理与格式化输出/hello.txt:
--------------------------------------------------------------------------------
1 | hello world
--------------------------------------------------------------------------------
/hello_macro/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/linked_list/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/unsafe_rust/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/world_hello/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/world_hello2/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/文件操作/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 | /a
3 |
--------------------------------------------------------------------------------
/配置文件/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 | *.json
3 |
--------------------------------------------------------------------------------
/web服务器/实践多线程_web服务器/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/web服务器/异步_web服务器/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/web服务器/异步多线程_web服务器/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/日志与监控/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 | /logs/
3 |
--------------------------------------------------------------------------------
/c调用rust/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 | /Cargo.lock
3 |
--------------------------------------------------------------------------------
/web服务器/单线程版本的_web_服务器/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/实现一个简单的redis/mini_redis/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/实现一个简单的redis/tokio_hello/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/实现一个简单的redis/tokio_select/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/实现一个简单的redis/tokio_stream/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/实现一个简单的redis/tokio_tcp/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/实现一个简单的redis/tokio_优雅的关闭/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/实现一个简单的redis/tokio_协作式调度/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/实现一个简单的redis/tokio_异步原理/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/文件操作/hello.txt:
--------------------------------------------------------------------------------
1 | hello
2 | www.xxxx.cnwww.xxxx.cn
--------------------------------------------------------------------------------
/文件操作/lorem_ipsum.txt:
--------------------------------------------------------------------------------
1 | xxxxxxxxxxxxxxxxxxxxxxxxx
--------------------------------------------------------------------------------
/sayhello_lib/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 | /Cargo.lock
3 |
--------------------------------------------------------------------------------
/study_test/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 | /Cargo.lock
3 |
--------------------------------------------------------------------------------
/timer_future/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 | /Cargo.lock
3 |
--------------------------------------------------------------------------------
/实现一个简单的redis/hello-my-redis/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/实现一个简单的redis/my-redis-stream/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/实现一个简单的redis/my-redis-共享状态/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/实现一个简单的redis/tokio_异步跟同步共存/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/rust_golang_ffi_demo/rustdemo/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 | /Cargo.lock
3 |
--------------------------------------------------------------------------------
/src/main.rs:
--------------------------------------------------------------------------------
1 | fn main() {
2 | println!("Hello, world!");
3 | }
4 |
--------------------------------------------------------------------------------
/hello_macro/hello_macro_derive/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 | /Cargo.lock
3 |
--------------------------------------------------------------------------------
/rust_golang_ffi_demo/golang/cgo/rustdemo.h:
--------------------------------------------------------------------------------
1 | char* rustdemo(char* name);
--------------------------------------------------------------------------------
/rust_golang_ffi_demo/golang/go.mod:
--------------------------------------------------------------------------------
1 | module go_rust
2 |
3 | go 1.20
4 |
--------------------------------------------------------------------------------
/配置文件/src/main.rs:
--------------------------------------------------------------------------------
1 | fn main() {
2 | println!("Hello, world!");
3 | }
4 |
--------------------------------------------------------------------------------
/日志与监控/src/main.rs:
--------------------------------------------------------------------------------
1 | fn main() {
2 | println!("Hello, world!");
3 | }
4 |
--------------------------------------------------------------------------------
/构建脚本/条件编译/src/main.rs:
--------------------------------------------------------------------------------
1 | fn main() {
2 | println!("Hello, world!");
3 | }
4 |
--------------------------------------------------------------------------------
/并发编程/examples/main5.rs:
--------------------------------------------------------------------------------
1 | fn main() {
2 | println!("Hello, world!");
3 | }
4 |
--------------------------------------------------------------------------------
/配置文件/examples/main3.rs:
--------------------------------------------------------------------------------
1 | fn main() {
2 | println!("Hello, world!");
3 | }
4 |
--------------------------------------------------------------------------------
/配置文件/examples/main4.rs:
--------------------------------------------------------------------------------
1 | fn main() {
2 | println!("Hello, world!");
3 | }
4 |
--------------------------------------------------------------------------------
/配置文件/examples/main5.rs:
--------------------------------------------------------------------------------
1 | fn main() {
2 | println!("Hello, world!");
3 | }
4 |
--------------------------------------------------------------------------------
/rust调用c/src/double.c:
--------------------------------------------------------------------------------
1 | int double_input(int input) {
2 | return input * 2;
3 | }
4 |
--------------------------------------------------------------------------------
/rust调用c/src/third.c:
--------------------------------------------------------------------------------
1 | int third_input(int input) {
2 | return input * 3;
3 | }
4 |
--------------------------------------------------------------------------------
/unsafe_rust/src/libadd.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/doraemonkeys/rust_code_snippets/HEAD/unsafe_rust/src/libadd.so
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.exe
2 | *.pdb
3 | *.vscode
4 | .vscode
5 | *.lib
6 | *.dll
7 | mytest/*
8 | .idea
9 | /target
10 |
--------------------------------------------------------------------------------
/study_test/tests/add_test.rs:
--------------------------------------------------------------------------------
1 | use study_test;
2 |
3 | #[test]
4 | fn it_adds_two() {
5 | assert_eq!(4, study_test::add_two(2));
6 | }
7 |
--------------------------------------------------------------------------------
/hello_macro/src/lib.rs:
--------------------------------------------------------------------------------
1 | // 在 `src/lib.rs` 中定义过程宏所需的 `HelloMacro` 特征和其关联函数:
2 | pub trait HelloMacro {
3 | fn hello_macro();
4 | }
5 | // 然后在 `src/main.rs` 中编写主体代码
6 |
--------------------------------------------------------------------------------
/复合类型/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "复合类型"
7 | version = "0.1.0"
8 |
--------------------------------------------------------------------------------
/文件操作/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "文件操作"
7 | version = "0.1.0"
8 |
--------------------------------------------------------------------------------
/智能指针/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "智能指针"
7 | version = "0.1.0"
8 |
--------------------------------------------------------------------------------
/模式匹配/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "模式匹配"
7 | version = "0.1.0"
8 |
--------------------------------------------------------------------------------
/流程控制/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "流程控制"
7 | version = "0.1.0"
8 |
--------------------------------------------------------------------------------
/生命周期/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "生命周期"
7 | version = "0.1.0"
8 |
--------------------------------------------------------------------------------
/所有权和借用/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "所有权和借用"
7 | version = "0.1.0"
8 |
--------------------------------------------------------------------------------
/minigrep/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "minigrep"
7 | version = "0.1.0"
8 |
--------------------------------------------------------------------------------
/方法_泛型_特征/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "方法_泛型_特征"
7 | version = "0.1.0"
8 |
--------------------------------------------------------------------------------
/unsafe_rust/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "unsafe_rust"
7 | version = "0.1.0"
8 |
--------------------------------------------------------------------------------
/world_hello/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "world_hello"
7 | version = "0.1.0"
8 |
--------------------------------------------------------------------------------
/world_hello2/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "world_hello2"
7 | version = "0.1.0"
8 |
--------------------------------------------------------------------------------
/web服务器/单线程版本的_web_服务器/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "单线程版本的_web_服务器"
7 | version = "0.1.0"
8 |
--------------------------------------------------------------------------------
/实现一个简单的redis/mini_redis/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "mini_redis"
7 | version = "0.1.0"
8 |
--------------------------------------------------------------------------------
/构建脚本/hello/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "hello-from-generated-code"
7 | version = "0.1.0"
8 |
--------------------------------------------------------------------------------
/文件操作/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "文件操作"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/智能指针/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "智能指针"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/模式匹配/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "模式匹配"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/流程控制/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "流程控制"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/生命周期/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "生命周期"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/minigrep/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "minigrep"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/web服务器/实践多线程_web服务器/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "practice_thread_web_server"
7 | version = "0.1.0"
8 |
--------------------------------------------------------------------------------
/所有权和借用/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "所有权和借用"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/构建脚本/条件编译/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "条件编译"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/复合类型/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "compound_types"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/构建脚本/链接系统库/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "libz-sys"
3 | version = "0.1.0"
4 | edition = "2024"
5 | #这里的 links = "z" 用于告诉 Cargo 我们想要链接到 libz 库,
6 | links = "z"
7 |
8 | [build-dependencies]
9 | pkg-config = "0.3.16"
10 |
--------------------------------------------------------------------------------
/unsafe_rust/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "unsafe_rust"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/world_hello/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "world_hello"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/world_hello2/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "world_hello2"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/方法_泛型_特征/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "method_generic_trait"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/web服务器/单线程版本的_web_服务器/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "单线程版本的_web_服务器"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/实现一个简单的redis/mini_redis/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "mini_redis"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/bytes/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "stu_bytes"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | bytes = "1"
10 |
--------------------------------------------------------------------------------
/猜数游戏/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "猜数游戏"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | rand = "0.8.5"
10 |
--------------------------------------------------------------------------------
/web服务器/异步_web服务器/hello.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Hello!
7 |
8 |
9 |
10 | Hello!
11 | Hi from Rust
12 |
13 |
14 |
--------------------------------------------------------------------------------
/循环引用与自引用/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "循环引用与自引用"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | ouroboros = "0.15.6"
10 |
--------------------------------------------------------------------------------
/timer_future/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "timer_future"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | futures = "0.3.5"
10 |
--------------------------------------------------------------------------------
/web服务器/单线程版本的_web_服务器/hello.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Hello!
7 |
8 |
9 |
10 | Hello!
11 | Hi from Rust
12 |
13 |
14 |
--------------------------------------------------------------------------------
/web服务器/实践多线程_web服务器/hello.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Hello!
7 |
8 |
9 |
10 | Hello!
11 | Hi from Rust
12 |
13 |
14 |
--------------------------------------------------------------------------------
/web服务器/异步多线程_web服务器/hello.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Hello!
7 |
8 |
9 |
10 | Hello!
11 | Hi from Rust
12 |
13 |
14 |
--------------------------------------------------------------------------------
/c调用rust/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "c-to-rust"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 |
7 | [lib]
8 | #name为编译生成之后的lib库的名字,生成lib2_3.a(或lib2_3.lib)静态库和其他一些编译之后东西
9 | name = "2_3"
10 | # 指定rustc编译成什么库类型,这里指定为静态库类型。
11 | crate-type = ["staticlib"]
12 |
--------------------------------------------------------------------------------
/web服务器/实践多线程_web服务器/404.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | 你好!
7 |
8 |
9 |
10 | 很抱歉!
11 | 由于运维删库跑路,我们的数据全部丢失,总监也已经准备跑路,88
12 |
13 |
14 |
--------------------------------------------------------------------------------
/web服务器/异步_web服务器/404.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | 你好!
7 |
8 |
9 |
10 | 很抱歉!
11 | 由于运维删库跑路,我们的数据全部丢失,总监也已经准备跑路,88
12 |
13 |
14 |
--------------------------------------------------------------------------------
/基本数据类型/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "基本数据类型"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | lazy_static = "1.4.0"
10 | num = "0.4.0"
11 |
--------------------------------------------------------------------------------
/web服务器/单线程版本的_web_服务器/404.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Hello!
7 |
8 |
9 |
10 | Oops!
11 | Sorry, I don't know what you're asking for.
12 |
13 |
14 |
--------------------------------------------------------------------------------
/web服务器/实践多线程_web服务器/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | #name = "实践多线程_web服务器"
3 | name = "practice_thread_web_server"
4 | version = "0.1.0"
5 | edition = "2024"
6 |
7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
8 |
9 | [dependencies]
10 |
--------------------------------------------------------------------------------
/web服务器/异步多线程_web服务器/404.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Hello!
7 |
8 |
9 |
10 | Oops!
11 | Sorry, I don't know what you're asking for.
12 |
13 |
14 |
--------------------------------------------------------------------------------
/实现一个简单的redis/tokio_tcp/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "tcp"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | tokio = { version = "1", features = ["full"] }
10 |
--------------------------------------------------------------------------------
/linked_list/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "linked_list"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | tokio = { version = "1.15.0", features = ["full"] }
10 |
--------------------------------------------------------------------------------
/构建脚本/hello/Cargo.toml:
--------------------------------------------------------------------------------
1 | # workspace = { members = ["链接系统库"] }
2 | [package]
3 | name = "hello-from-generated-code"
4 | version = "0.1.0"
5 | edition = "2024"
6 |
7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
8 |
9 | [dependencies]
10 |
--------------------------------------------------------------------------------
/实现一个简单的redis/tokio_优雅的关闭/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "tokio_优雅的关闭"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | tokio = { version = "1", features = ["full"] }
10 |
--------------------------------------------------------------------------------
/实现一个简单的redis/tokio_异步原理/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "tokio_异步原理"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | tokio = { version = "1", features = ["full"] }
10 |
--------------------------------------------------------------------------------
/实现一个简单的redis/tokio_select/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "tokio_select"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | tokio = { version = "1", features = ["full"] }
10 |
--------------------------------------------------------------------------------
/hello_macro/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "hello_macro"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | hello_macro_derive = { path = "./hello_macro_derive" }
10 | syn = "2.0.37"
11 |
--------------------------------------------------------------------------------
/sayhello_lib/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "sayhello_lib"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
10 | # [lib]
11 | # name = "my_library"
12 | # crate-type = ["cdylib"]
13 |
--------------------------------------------------------------------------------
/实现一个简单的redis/tokio_异步跟同步共存/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "异步跟同步共存"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | tokio = { version = "1", features = ["full"] }
10 | bytes = "1"
11 |
--------------------------------------------------------------------------------
/rust_golang_ffi_demo/golang/mainc:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | extern char* rustdemo(char* name);
4 |
5 | // 将rustdemo.dll动态链接库放到当前目录下
6 | // gcc -o test_c main.c rustdemo.dll
7 | int main() {
8 | char* name = "Rust";
9 | char* result = rustdemo(name);
10 | printf("%s\n", result);
11 | return 0;
12 | }
13 |
--------------------------------------------------------------------------------
/hello_macro/hello_macro_derive/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "hello_macro_derive"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # syn 和 quote 依赖包都是定义过程宏所必需的,
7 | # 同时,还需要在 [lib] 中将过程宏的开关开启 : proc-macro = true。
8 | [lib]
9 | proc-macro = true
10 |
11 | [dependencies]
12 | syn = "2.0"
13 | quote = "1.0"
14 | proc-macro2 = "1.0"
15 |
--------------------------------------------------------------------------------
/web服务器/异步_web服务器/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "异步_web服务器"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | futures = "0.3.28"
10 | [dependencies.async-std]
11 | version = "1.12"
12 | features = ["attributes"]
13 |
--------------------------------------------------------------------------------
/web服务器/异步多线程_web服务器/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "异步多线程_web服务器"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | futures = "0.3.28"
10 | [dependencies.async-std]
11 | version = "1.6"
12 | features = ["attributes"]
13 |
--------------------------------------------------------------------------------
/rust调用c/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "rust-to-c"
3 | version = "0.1.0"
4 | edition = "2024"
5 | # Cargo 会先编译和执行该构建脚本,然后再去构建整个项目。
6 | build = "build.rs"
7 |
8 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
9 |
10 | [dependencies]
11 | libc = "0.2"
12 |
13 | [build-dependencies]
14 | cc = "1.0"
15 |
--------------------------------------------------------------------------------
/实现一个简单的redis/my-redis-stream/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "my-redis-stream"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | tokio = { version = "1", features = ["full"] }
10 | tokio-stream = "0.1"
11 | mini-redis = "0.4"
12 |
--------------------------------------------------------------------------------
/错误处理与格式化输出/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "错误处理与格式化输出"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | sayhello_lib = { path = "E:/Doraemon/IT/Rust/study/sayhello_lib" }
10 | thiserror = "1.0"
11 | anyhow = "1.0"
12 | sqlx = "0.8"
13 |
--------------------------------------------------------------------------------
/构建脚本/链接系统库/src/lib.rs:
--------------------------------------------------------------------------------
1 | use std::os::raw::{c_uint, c_ulong};
2 |
3 | extern "C" {
4 | pub fn crc32(crc: c_ulong, buf: *const u8, len: c_uint) -> c_ulong;
5 | }
6 |
7 | #[test]
8 | #[cfg(target_os = "linux")]
9 | fn test_crc32() {
10 | let s = "hello";
11 | unsafe {
12 | assert_eq!(crc32(0, s.as_ptr(), s.len() as c_uint), 0x3610a686);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/sayhello_lib/src/lib.rs:
--------------------------------------------------------------------------------
1 | pub fn add(left: usize, right: usize) -> usize {
2 | left + right
3 | }
4 |
5 | pub fn say_hello(name: &str) {
6 | println!("Hello, {}!", name);
7 | }
8 |
9 | #[cfg(test)]
10 | mod tests {
11 | use super::*;
12 |
13 | #[test]
14 | fn it_works() {
15 | let result = add(2, 2);
16 | assert_eq!(result, 4);
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/minigrep/tests/search.rs:
--------------------------------------------------------------------------------
1 | #[cfg(test)]
2 | mod tests {
3 |
4 | #[test]
5 | fn one_result() {
6 | let query = "fast";
7 | let contents = "\
8 | Rust:
9 | safe, fast, productive.
10 | Pick three.";
11 |
12 | assert_eq!(
13 | vec!["safe, fast, productive."],
14 | minigrep::search(query, contents)
15 | );
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/宏编程/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "宏编程"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
10 | hello_macro = { path = "E:/Doraemon/IT/Rust/study/hello_macro" }
11 | hello_macro_derive = { path = "E:/Doraemon/IT/Rust/study/hello_macro/hello_macro_derive" }
12 |
--------------------------------------------------------------------------------
/并发编程/examples/alternate.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func worker(notifyCh chan int, id int) {
6 | for i := range notifyCh {
7 | fmt.Printf("worker %d: %d\n", id, i)
8 | notifyCh <- i + 1
9 | }
10 | }
11 |
12 | // 两个线程/协程交替打印数字
13 | func main() {
14 | notifyCh := make(chan int)
15 | go worker(notifyCh, 1)
16 | notifyCh <- 0
17 | worker(notifyCh, 2)
18 | }
19 |
--------------------------------------------------------------------------------
/实现一个简单的redis/tokio_hello/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "tokio_hello"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | tokio = { version = "1.43", features = ["full"] }
10 | mini-redis = "0.4"
11 |
12 | [[example]]
13 | name = "example"
14 | path = "examples/*"
15 |
--------------------------------------------------------------------------------
/minigrep/poem.txt:
--------------------------------------------------------------------------------
1 | I'm nobody! Who are you?
2 | 我啥也不是,你呢?
3 | Are you nobody, too?
4 | 牛逼如你也是无名之辈吗?
5 | Then there's a pair of us - don't tell!
6 | 那我们就是天生一对,嘘!别说话!
7 | They'd banish us, you know.
8 | 你知道,我们不属于这里。
9 | How dreary to be somebody!
10 | 因为这里属于没劲的大人物!
11 | How public, like a frog
12 | 他们就像青蛙一样呱噪,
13 | To tell your name the livelong day
14 | 成天将自己的大名
15 | To an admiring bog!
16 | 传遍整个无聊的沼泽!
17 |
--------------------------------------------------------------------------------
/实现一个简单的redis/tokio_stream/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "tokio_stream"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | tokio = { version = "1", features = ["full"] }
10 | tokio-stream = "0.1"
11 | async-stream = "0.3"
12 | futures-util = "0.3"
13 | futures-core = "0.3"
14 |
--------------------------------------------------------------------------------
/实现一个简单的redis/tokio_协作式调度/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "tokio_协作式调度"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | tokio = { version = "1.16.1", features = ["full"] }
10 | rand = "0.8.4"
11 |
12 |
13 | [[example]]
14 | name = "example1"
15 | path = "examples/example1.rs"
16 |
--------------------------------------------------------------------------------
/实现一个简单的redis/my-redis-共享状态/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "my-redis2"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | tokio = { version = "1", features = ["full"] }
10 | mini-redis = "0.4"
11 | bytes = "1"
12 |
13 |
14 | [[example]]
15 | name = "hello-redis"
16 | path = "examples/hello-redis.rs"
17 |
--------------------------------------------------------------------------------
/异步编程/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "异步编程"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | futures = "0.3.5"
10 | rand = "0.8.5"
11 | tokio = { version = "0.2", features = ["full"] }
12 | timer_future = { path = "E:/Doraemon/IT/Rust/study/timer_future" }
13 | pin-utils = "0.1.0"
14 | async-trait = "0.1"
15 |
--------------------------------------------------------------------------------
/配置文件/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "配置文件"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | serde = { version = "1.0", features = ["derive"] }
10 | serde_json = "1.0"
11 | serde_yaml = "0.9"
12 | ini = "1"
13 | config = "0.13"
14 | toml = "0.8"
15 |
16 | [[example]]
17 | name = "example1"
18 | path = "examples/*"
19 |
--------------------------------------------------------------------------------
/bytes/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "bytes"
7 | version = "1.4.0"
8 | source = "registry+https://github.com/rust-lang/crates.io-index"
9 | checksum = "89b2fd2a0dcf38d7971e2194b6b6eebab45ae01067456a7fd93d5547a61b70be"
10 |
11 | [[package]]
12 | name = "stu_bytes"
13 | version = "0.1.0"
14 | dependencies = [
15 | "bytes",
16 | ]
17 |
--------------------------------------------------------------------------------
/rust调用c/src/main.rs:
--------------------------------------------------------------------------------
1 | extern crate libc;
2 |
3 | unsafe extern "C" {
4 | fn double_input(input: libc::c_int) -> libc::c_int;
5 | fn third_input(input: libc::c_int) -> libc::c_int;
6 | }
7 |
8 | fn main() {
9 | let input = 4;
10 | let output = unsafe { double_input(input) };
11 | let output2: i32 = unsafe { third_input(input) };
12 | println!("{} * 3 = {}", input, output2);
13 | println!("{} * 2 = {}", input, output);
14 | }
15 |
--------------------------------------------------------------------------------
/并发编程/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "并发编程"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | crossbeam-channel = "0.5.8"
10 | crossbeam-utils = "0.8.15"
11 | thread_local = "1.1.7"
12 | tokio = { version = "1", features = ["full"] }
13 | lazy_static = "1.4"
14 |
15 | [[example]]
16 | name = "example1"
17 | path = "examples/*"
18 |
--------------------------------------------------------------------------------
/构建脚本/hello/src/main.rs:
--------------------------------------------------------------------------------
1 | include!(concat!(env!("OUT_DIR"), "/hello.rs"));
2 | // env! 用于在编译时展开为指定的环境变量的值。
3 | // concat! 用于将字符串字面量连接起来成为一个新的&str。
4 | // include!将文件内容插入到这里。
5 |
6 | fn main() {
7 | println!("{}", message());
8 | env!("OUT_DIR");
9 | }
10 |
11 | // 这里才是体现真正技术的地方,我们联合使用 rustc 定义的 include! 以及 concat! 和 env! 宏,
12 | // 将生成的代码文件( hello.rs ) 纳入到我们项目的编译流程中。
13 |
14 | // 例子虽然很简单,但是它清晰地告诉了我们该如何生成代码文件以及将这些代码文件纳入到编译中来,
15 | // 大家以后有需要只要回头看看即可。
16 |
--------------------------------------------------------------------------------
/构建脚本/链接系统库/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "libz-sys"
7 | version = "0.1.0"
8 | dependencies = [
9 | "pkg-config",
10 | ]
11 |
12 | [[package]]
13 | name = "pkg-config"
14 | version = "0.3.29"
15 | source = "registry+https://github.com/rust-lang/crates.io-index"
16 | checksum = "2900ede94e305130c13ddd391e0ab7cbaeb783945ae07a279c268cb05109c6cb"
17 |
--------------------------------------------------------------------------------
/c调用rust/src/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | extern int32_t double_input(int32_t input);
5 | extern int32_t third_input(int32_t input);
6 |
7 | // gcc -o test_c main.c 2_3.lib
8 | // ./test_c
9 | int main() {
10 | int input = 4;
11 | int output = double_input(input);
12 | int output2 = third_input(input);
13 | printf("%d * 2 = %d\n", input, output);
14 | printf("%d * 3 = %d\n", input, output2);
15 | return 0;
16 | }
17 |
--------------------------------------------------------------------------------
/study_test/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "study_test"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
10 | # standard crate data is left out
11 | [dev-dependencies]
12 | pretty_assertions = "1"
13 | criterion = "0.3"
14 |
15 |
16 | # cargo bench 命令会自动运行 benchmarks 目录下的所有基准测试
17 | [[bench]]
18 | name = "my_benchmark"
19 | harness = false
20 |
--------------------------------------------------------------------------------
/rust_golang_ffi_demo/rustdemo/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "rustdemo"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | # [lib]
9 | # #name为编译生成之后的lib库的名字,生成libsay_hello.a(或libsay_hello.lib)静态库和其他一些编译之后东西
10 | # name = "say_hello"
11 | # # 指定rustc编译成什么库类型,这里指定为静态库类型。
12 | # crate-type = ["staticlib"]
13 |
14 | # [dependencies]
15 | # libc = "0.2"
16 |
17 | [lib]
18 | crate-type = ["cdylib"]
19 | [dependencies]
20 | libc = "0.2"
21 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## Rust Code Snippets
4 |
5 | Rust语言圣经代码片段合集,带知识点注释与更多扩展。
6 |
7 |
8 |
9 | 自己用来快速搜索回顾相关语法与知识点。
10 |
11 |
12 | 食用指南:跟着程序执行的流程学习。
13 |
14 |
15 | ## 相关链接
16 |
17 | - [Rust语言圣经](https://course.rs/)
18 | - [通过例子学 Rust 中文版](https://rustwiki.org/zh-CN/rust-by-example/)
19 | - [Rust 程序设计语言 中文版](https://rustwiki.org/zh-CN/book/)
20 | - [Rust 官方文档中文教程](https://rustwiki.org/)
21 | - [Rust 参考手册 中文版](https://rustwiki.org/zh-CN/reference/)
22 | - [Rust Cookbook 中文版](https://rustwiki.org/zh-CN/rust-cookbook/)
23 | - [Rust 标准库 中文文档](https://rustwiki.org/zh-CN/std/)
--------------------------------------------------------------------------------
/study_test/benches/my_benchmark.rs:
--------------------------------------------------------------------------------
1 | use criterion::{Criterion, black_box, criterion_group, criterion_main};
2 |
3 | fn fibonacci(n: u64) -> u64 {
4 | match n {
5 | 0 => 1,
6 | 1 => 1,
7 | n => fibonacci(n - 1) + fibonacci(n - 2),
8 | }
9 | }
10 |
11 | // https://bheisler.github.io/criterion.rs/book/getting_started.html
12 | fn criterion_benchmark(c: &mut Criterion) {
13 | c.bench_function("fib 20", |b| b.iter(|| fibonacci(black_box(20))));
14 | }
15 |
16 | criterion_group!(benches, criterion_benchmark);
17 | criterion_main!(benches);
18 |
--------------------------------------------------------------------------------
/构建脚本/链接系统库/build.rs:
--------------------------------------------------------------------------------
1 | fn main() {
2 | pkg_config::Config::new().probe("zlib").unwrap();
3 | println!("cargo:rerun-if-changed=build.rs");
4 | }
5 |
6 | // 代码很清晰,也很简洁,这里就不再过多介绍,
7 | // 运行 cargo build --vv 来看看部分结果( 系统中需要已经安装 libz 库):
8 |
9 | // [libz-sys 0.1.0] cargo:rustc-link-search=native=/usr/lib
10 | // [libz-sys 0.1.0] cargo:rustc-link-lib=z
11 | // [libz-sys 0.1.0] cargo:rerun-if-changed=build.rs
12 | // 非常棒,pkg-config 帮助我们找到了目标库,并且还告知了 Cargo 所有需要的信息!
13 |
14 | // 实际使用中,我们需要做的比上面的代码更多,
15 | // 例如 libz-sys 包会先检查环境变量 LIBZ_SYS_STATIC 或者 static feature,
16 | // 然后基于源码去构建 libz,而不是直接去使用系统库。
17 |
--------------------------------------------------------------------------------
/并发编程/examples/alternate1.rs:
--------------------------------------------------------------------------------
1 | use std::sync::{Mutex, mpsc};
2 |
3 | fn worker(sender: mpsc::SyncSender, receiver: &Mutex>, id: i32) {
4 | loop {
5 | let i = receiver.lock().unwrap().recv().unwrap();
6 | println!("worker {}: {}", id, i);
7 | sender.send(i + 1).unwrap();
8 | }
9 | }
10 |
11 | // 两个线程/协程交替打印数字
12 | fn main() {
13 | let (tx, rx) = mpsc::sync_channel(0);
14 | let rx = Mutex::new(rx);
15 | std::thread::scope(|s| {
16 | s.spawn(|| worker(tx.clone(), &rx, 1));
17 | tx.send(0).unwrap();
18 | worker(tx.clone(), &rx, 2);
19 | });
20 | }
21 |
--------------------------------------------------------------------------------
/world_hello/src/main.rs:
--------------------------------------------------------------------------------
1 | fn greet_world() {
2 | // Rust 原生支持 UTF-8 编码的字符串
3 | let southern_germany = "Grüß Gott!";
4 | let chinese = "世界,你好";
5 | // let english = "World, hello";
6 | let english = "World, hello";
7 |
8 | // Rust为数组实现了IntoIterator trait,我们可以直接对一个数组进行迭代
9 | let regions = [southern_germany, chinese, english];
10 | for region in regions {
11 | // !是一个格式化宏,用于格式化字符串
12 | // 对于 `println` 来说,我们没有使用其它语言惯用的 `%s`、`%d` 来做输出占位符,而是使用 `{}`,
13 | // 因为 Rust 在底层帮我们做了大量工作,会自动识别输出数据的类型
14 | println!("{}", ®ion);
15 | }
16 | }
17 |
18 | fn main() {
19 | greet_world();
20 | }
21 |
--------------------------------------------------------------------------------
/rust调用c/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "cc"
7 | version = "1.0.79"
8 | source = "registry+https://github.com/rust-lang/crates.io-index"
9 | checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f"
10 |
11 | [[package]]
12 | name = "libc"
13 | version = "0.2.142"
14 | source = "registry+https://github.com/rust-lang/crates.io-index"
15 | checksum = "6a987beff54b60ffa6d51982e1aa1146bc42f19bd26be28b0586f252fccf5317"
16 |
17 | [[package]]
18 | name = "rust-to-c"
19 | version = "0.1.0"
20 | dependencies = [
21 | "cc",
22 | "libc",
23 | ]
24 |
--------------------------------------------------------------------------------
/minigrep/src/main.rs:
--------------------------------------------------------------------------------
1 | // cargo run -- searchstring example-filename.txt
2 |
3 | // cargo run -- How poem.txt
4 |
5 | // $env:IGNORE_CASE=1;cargo run -- to poem.txt
6 | use minigrep::Config;
7 | fn main() {
8 | let args: Vec = std::env::args().collect();
9 | let query_cnf = Config::build(args.iter()).unwrap_or_else(|err| {
10 | eprintln!("Problem parsing arguments: {err}");
11 | std::process::exit(1);
12 | });
13 | println!("Searching for {}", query_cnf.query);
14 | println!("In file {}", query_cnf.file_path);
15 |
16 | if let Err(e) = minigrep::run(&query_cnf) {
17 | eprintln!("Application error: {e}");
18 | std::process::exit(1);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/日志与监控/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "日志与监控"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | log = "0.4"
10 | tracing = "0.1"
11 | tracing-subscriber = { version = "0.3", features = [
12 | "env-filter",
13 | "fmt",
14 | "time",
15 | "local-time",
16 | ] }
17 | env_logger = "0.10"
18 | serde_json = "1.0"
19 | serde = { version = "1.0", features = ["derive"] }
20 | hex = "0.4"
21 | tokio = { version = "1.0", features = ["full"] }
22 | tracing-appender = "0.2"
23 | color-eyre = "0.6"
24 | tracing-error = "0.2.0"
25 | chrono = "0.4.31"
26 |
27 | [[example]]
28 | name = "example1"
29 | path = "examples/*"
30 |
--------------------------------------------------------------------------------
/c调用rust/src/lib.rs:
--------------------------------------------------------------------------------
1 | // rustc默认编译产生rust自用的rlib格式库,要让rustc产生动态链接库或者静态链接库,需要显式指定。
2 |
3 | // 方法1: 在文件中指定。
4 | // 在文件头加上#![crate_type = “foo”],
5 | // 其中foo的可选类型有bin, lib, rlib, dylib, staticlib,
6 | // 默认(将由rustc自己决定), rlib格式,动态链接库,静态链接库。
7 | // 方法2: 编译时给rustc 传–crate-type参数,参数内容同上。
8 | // 方法3: 使用cargo,指定crate-type = [“foo”], foo可选类型同1。
9 |
10 | // #[no_mangle] 的作用是由于rust支持重载,所以函数名会被编译器进行混淆,
11 | // 就像c++一样,加上这个就可以不修改函数名。
12 |
13 | #![crate_type = "staticlib"] // 指定rustc编译成什么库类型,这里指定为静态库类型。
14 |
15 | #[unsafe(no_mangle)]
16 | pub extern "C" fn double_input(input: i32) -> i32 {
17 | input * 2
18 | }
19 |
20 | #[unsafe(no_mangle)]
21 | pub extern "C" fn third_input(input: i32) -> i32 {
22 | input * 3
23 | }
24 |
25 | // cargo build --release
26 |
--------------------------------------------------------------------------------
/实现一个简单的redis/tokio_hello/examples/main2.rs:
--------------------------------------------------------------------------------
1 | use tokio::time::sleep;
2 |
3 | #[tokio::main]
4 | async fn main() {
5 | let data = vec![1, 2, 3];
6 | let data_ref = &data; // Borrow the data
7 |
8 | tokio::task::spawn(async move {
9 | let mut interval = tokio::time::interval(std::time::Duration::from_millis(200));
10 | loop {
11 | interval.tick().await;
12 | println!("tick");
13 | }
14 | });
15 |
16 | tokio::task::unconstrained(async {
17 | sleep(std::time::Duration::from_secs(2)).await;
18 | // Access the borrowed data here
19 | println!("Data inside task: {:?}", data_ref);
20 | })
21 | .await;
22 |
23 | println!("Final data: {:?}", data); // Still accessible here
24 | }
25 |
--------------------------------------------------------------------------------
/复合类型/src/tuple.rs:
--------------------------------------------------------------------------------
1 | pub fn study_tuple() {
2 | println!("-----------------元组-----------------");
3 | // 元组是由多种类型组合到一起形成的,因此它是复合类型,元组的长度是固定的,元组中元素的顺序也是固定的。
4 | let tup: (i32, f64, u8) = (500, 6.4, 1);
5 | dbg!(tup);
6 | // 用模式匹配解构元组
7 | println!("-----------------用模式匹配解构元组-----------------");
8 | let (_x, y, _z) = tup;
9 | println!("The value of y is: {}", y);
10 | // 用 . 来访问元组
11 | println!("-----------------用 . 来访问元组-----------------");
12 | let five_hundred = tup.0;
13 | let six_point_four = tup.1;
14 | let one = tup.2;
15 | println!(
16 | "five_hundred: {}, six_point_four: {}, one: {}",
17 | five_hundred, six_point_four, one
18 | );
19 | // 函数返回多个值可以使用元组
20 | println!("-----------------函数返回多个值可以使用元组-----------------");
21 | let (x, y) = return_tuple();
22 | println!("x: {}, y: {}", x, y);
23 | }
24 |
25 | fn return_tuple() -> (i32, i32) {
26 | (1, 2)
27 | }
28 |
--------------------------------------------------------------------------------
/并发编程/examples/alternate3.rs:
--------------------------------------------------------------------------------
1 | use tokio::sync::oneshot;
2 |
3 | #[derive(Debug)]
4 | struct DataSender {
5 | data: T,
6 | sender: Box>>,
7 | }
8 |
9 | async fn worker(mut receiver: oneshot::Receiver>, id: i32) {
10 | loop {
11 | let s = receiver.await.unwrap();
12 | println!("worker {}: {}", id, s.data);
13 | let (tx, rx) = oneshot::channel();
14 | s.sender
15 | .send(DataSender {
16 | data: s.data + 1,
17 | sender: Box::new(tx),
18 | })
19 | .unwrap();
20 | receiver = rx;
21 | }
22 | }
23 |
24 | // 两个线程/协程交替打印数字
25 | // Rust异步实现
26 | #[tokio::main]
27 | async fn main() {
28 | let (tx, rx) = oneshot::channel();
29 | let (tx2, rx2) = oneshot::channel();
30 | tokio::spawn(worker(rx, 1));
31 | tx.send(DataSender {
32 | data: 0,
33 | sender: Box::new(tx2),
34 | })
35 | .unwrap();
36 | worker(rx2, 2).await
37 | }
38 |
--------------------------------------------------------------------------------
/实现一个简单的redis/mini_redis/src/main.rs:
--------------------------------------------------------------------------------
1 | fn main() {
2 | println!("Hello, world!");
3 | }
4 |
5 | // 虽然 tokio 对于大多数需要并发的项目都是非常适合的,但是确实有一些场景它并不适合使用:
6 | // - 并行运行 CPU 密集型的任务。tokio 非常适合于 IO 密集型任务,
7 | // 这些 IO 任务的绝大多数时间都用于阻塞等待 IO 的结果,而不是刷刷刷的单烤 CPU。
8 | // 如果你的应用是 CPU 密集型(例如并行计算),建议使用 rayon,
9 | // 当然,对于其中的 IO 任务部分,你依然可以混用 tokio
10 | // - 读取大量的文件。读取文件的瓶颈主要在于操作系统,因为 OS 没有提供异步文件读取接口,
11 | // 大量的并发并不会提升文件读取的并行性能,反而可能会造成不可忽视的性能损耗,
12 | // 因此建议使用线程(或线程池)的方式
13 | // - 发送少量 HTTP 请求。tokio 的优势是给予你并发处理大量任务的能力,
14 | // 对于这种轻量级 HTTP 请求场景,tokio 除了增加你的代码复杂性,并无法带来什么额外的优势。
15 | // 因此,对于这种场景,你可以使用 reqwest库,它会更加简单易用。
16 |
17 | // 若大家使用 tokio,那 CPU 密集的任务尤其需要用线程的方式去处理,
18 | // 例如使用 spawn_blocking 创建一个阻塞的线程去完成相应 CPU 密集任务。
19 | // 原因是:tokio 是协作式的调度器,如果某个 CPU 密集的异步任务是通过 tokio 创建的,
20 | // 那理论上来说,该异步任务需要跟其它的异步任务交错执行,最终大家都得到了执行,皆大欢喜。
21 | // 但实际情况是,CPU 密集的任务很可能会一直霸着着 CPU,此时 tokio 的调度方式决定了该任务会一直被执行,
22 | // 这意味着,其它的异步任务无法得到执行的机会,最终这些任务都会因为得不到资源而饿死。
23 | // 而使用 spawn_blocking 后,会创建一个单独的 OS 线程,该线程并不会被 tokio 所调度( 被 OS 所调度 ),
24 | // 因此它所执行的 CPU 密集任务也不会导致 tokio 调度的那些异步任务被饿死
25 |
--------------------------------------------------------------------------------
/方法_泛型_特征/src/inheritance.rs:
--------------------------------------------------------------------------------
1 | // 基类
2 | struct Animal {
3 | age: i32,
4 | }
5 |
6 | impl Animal {
7 | fn new(age: i32) -> Self {
8 | Animal { age }
9 | }
10 |
11 | // 基类方法,下面的代码中,它将会被子类复用
12 | fn speak(&self) {
13 | println!("I'm an animal. Age = {}", self.age);
14 | }
15 | }
16 |
17 | // 子类
18 | struct Dog {
19 | supper: Animal,
20 | _name: String,
21 | }
22 |
23 | impl Dog {
24 | fn new(name: String, age: i32) -> Self {
25 | Dog {
26 | supper: Animal::new(age),
27 | _name: name,
28 | }
29 | }
30 |
31 | // 实现"复用父类的方法"
32 | fn speak(&self) {
33 | self.supper.speak();
34 | }
35 | }
36 |
37 | pub fn study_inheritance() {
38 | println!("----------------继承----------------");
39 | // Rust 不支持继承,但可以通过子类嵌套父类的方式,实现类似“继承”的效果,跟Go语言挺像的。
40 | // Don't look for tricks to simulate inheritance. Rust isn't designed this way and
41 | // it doesn't help to try to make it OOP.
42 | // 尽量不要去模拟继承,Rust并不是为了这样设计的,也不会帮助你去尝试OOP。
43 | let dog = Dog::new(String::from("Tom"), 2);
44 | dog.speak();
45 | }
46 |
--------------------------------------------------------------------------------
/实现一个简单的redis/tokio_异步原理/src/main.rs:
--------------------------------------------------------------------------------
1 | use std::future::Future;
2 | use std::pin::Pin;
3 | use std::task::{Context, Poll};
4 | use std::time::{Duration, Instant};
5 |
6 | // 下面来一起实现个五脏俱全的 `Future`,它将:
7 | // 1. 等待某个特定时间点的到来 2. 在标准输出打印文本 3. 生成一个字符串
8 | struct Delay {
9 | when: Instant,
10 | }
11 |
12 | // 为我们的 Delay 类型实现 Future 特征
13 | impl Future for Delay {
14 | type Output = &'static str;
15 |
16 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<&'static str> {
17 | if Instant::now() >= self.when {
18 | // 时间到了,Future 可以结束
19 | println!("Hello world");
20 | // Future 执行结束并返回 "done" 字符串
21 | Poll::Ready("done")
22 | } else {
23 | // 目前先忽略下面这行代码
24 | cx.waker().wake_by_ref();
25 | Poll::Pending
26 | }
27 | }
28 | }
29 |
30 | #[tokio::main]
31 | async fn main() {
32 | let when = Instant::now() + Duration::from_millis(10);
33 | let future = Delay { when };
34 |
35 | // 运行并等待 Future 的完成
36 | let out = future.await;
37 |
38 | // 判断 Future 返回的字符串是否是 "done"
39 | assert_eq!(out, "done");
40 | }
41 |
--------------------------------------------------------------------------------
/实现一个简单的redis/tokio_tcp/src/bin/server.rs:
--------------------------------------------------------------------------------
1 | // 举一个tokio官方的代码例子,这段代码实现了一个tcp server,会将客户端发来的数据原封不动的发回去:
2 | use tokio::io::{AsyncReadExt, AsyncWriteExt};
3 | use tokio::net::{TcpListener, TcpStream};
4 |
5 | use std::error::Error;
6 |
7 | // cargo run --bin server
8 | #[tokio::main]
9 | async fn main() -> Result<(), Box> {
10 | let listener = TcpListener::bind("127.0.0.1:8081").await?;
11 |
12 | loop {
13 | let (socket, socket_addr) = listener.accept().await?;
14 | println!("accept socket: {:?}", socket_addr);
15 | tokio::spawn(handler(socket));
16 | }
17 | }
18 |
19 | async fn handler(mut socket: TcpStream) {
20 | let mut buf = vec![0; 1024];
21 |
22 | loop {
23 | let n = socket
24 | .read(&mut buf)
25 | .await
26 | .expect("failed to read data from socket");
27 |
28 | if n == 0 {
29 | return;
30 | }
31 | println!("recv: {}", String::from_utf8_lossy(&buf[..n]).trim());
32 | socket
33 | .write_all(&buf[0..n])
34 | .await
35 | .expect("failed to write data to socket");
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/实现一个简单的redis/tokio_hello/examples/main6.rs:
--------------------------------------------------------------------------------
1 | use std::time::Instant;
2 | use tokio::task;
3 | use tokio::time::{Duration, sleep};
4 | #[tokio::main(flavor = "current_thread")]
5 | async fn main() {
6 | let now = Instant::now();
7 |
8 | let regular_task = async move {
9 | println!("Regular task: Started,{}", now.elapsed().as_millis());
10 | sleep(Duration::from_millis(500)).await;
11 | println!("Regular task: Resumed,{}", now.elapsed().as_millis());
12 | };
13 |
14 | tokio::spawn(regular_task);
15 |
16 | let unconstrained_task = task::unconstrained(async {
17 | println!(
18 | "Unconstrained task: Before sleep,{}",
19 | now.elapsed().as_millis()
20 | );
21 | // ???
22 | sleep(Duration::from_secs(1)).await;
23 | println!(
24 | "Unconstrained task: After sleep,{}",
25 | now.elapsed().as_millis()
26 | );
27 |
28 | println!("Unconstrained task: Before yield_now");
29 | task::yield_now().await;
30 | println!("Unconstrained task: After yield_now");
31 | });
32 |
33 | unconstrained_task.await;
34 | println!("Main task complete");
35 | }
36 |
--------------------------------------------------------------------------------
/实现一个简单的redis/hello-my-redis/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "my-redis"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | # Tokio 有很多功能和特性,例如 TCP,UDP,Unix sockets,同步工具,多调度类型等等,
10 | # 不是每个应用都需要所有的这些特性。为了优化编译时间和最终生成可执行文件大小、内存占用大小,
11 | # 应用可以对这些特性进行可选引入。
12 | # 而这里为了演示的方便,我们使用 full ,表示直接引入所有的特性。
13 | tokio = { version = "1", features = ["full"] }
14 | mini-redis = "0.4"
15 |
16 |
17 | # 示例对象的文件在根目录下的 examples 目录中。既然是示例,自然是使用项目中的库对象的功能进行演示。
18 | # 示例对象编译后的文件会存储在 target/debug/examples 目录下。
19 | # 如上所示,示例对象可以使用库对象的公共 API,也可以通过 [dependencies] 来引入外部的依赖库。
20 |
21 | # 默认情况下,示例对象都是可执行的二进制文件( 带有 fn main() 函数入口),
22 | # 毕竟例子是用来测试和演示我们的库对象,是用来运行的。而你完全可以将示例对象改成库的类型:
23 | # [[example]]
24 | # name = "foo"
25 | # crate-type = ["staticlib"]
26 | # 如果想要指定运行某个示例对象,可以使用 cargo run --example 命令。
27 | # 如果是库类型的示例对象,则可以使用 cargo build --example 进行构建。
28 | # 与此类似,还可以使用 cargo install --example 来将
29 | # 示例对象编译出的可执行文件安装到默认的目录中,将该目录添加到 $PATH 环境变量中,
30 | # 就可以直接全局运行安装的可执行文件。
31 |
32 | # 最后,cargo test 命令默认会对示例对象进行编译,以防止示例代码因为长久没运行,导致严重过期以至于无法运行。
33 | [[example]]
34 | name = "hello-redis"
35 | path = "examples/hello-redis.rs"
36 |
--------------------------------------------------------------------------------
/实现一个简单的redis/tokio_异步跟同步共存/src/other.rs:
--------------------------------------------------------------------------------
1 | use tokio::runtime::Builder;
2 | use tokio::sync::mpsc;
3 |
4 | pub struct Task {
5 | pub name: String,
6 | // 一些信息用于描述该任务
7 | }
8 |
9 | async fn handle_task(task: Task) {
10 | println!("Got task {}", task.name);
11 | }
12 |
13 | #[derive(Clone)]
14 | pub struct TaskSpawner {
15 | spawn: mpsc::Sender,
16 | }
17 |
18 | impl TaskSpawner {
19 | pub fn new() -> TaskSpawner {
20 | // 创建一个消息通道用于通信
21 | let (send, mut recv) = mpsc::channel(16);
22 |
23 | let rt = Builder::new_current_thread().enable_all().build().unwrap();
24 |
25 | std::thread::spawn(move || {
26 | rt.block_on(async move {
27 | while let Some(task) = recv.recv().await {
28 | tokio::spawn(handle_task(task));
29 | }
30 |
31 | // 一旦所有的发送端超出作用域被 drop 后,`.recv()` 方法会返回 None,同时 while 循环会退出,然后线程结束
32 | });
33 | });
34 |
35 | TaskSpawner { spawn: send }
36 | }
37 |
38 | pub fn spawn_task(&self, task: Task) {
39 | match self.spawn.blocking_send(task) {
40 | Ok(()) => println!("spawn_task Ok"),
41 | Err(_) => panic!("The shared runtime has shut down."),
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/rust_golang_ffi_demo/golang/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | // #cgo CFLAGS: -I./cgo
4 | // #cgo LDFLAGS: -L${SRCDIR} -lrustdemo
5 | // #include "rustdemo.h"
6 | import "C"
7 | import (
8 | "fmt"
9 | )
10 |
11 | func main() {
12 | name := C.CString("golang")
13 | result := C.GoString(C.rustdemo(name))
14 | fmt.Printf("result: %s\n", result)
15 | }
16 |
17 | // unsafe 调用 dll
18 | /*
19 | package main
20 |
21 | import (
22 | "C"
23 | "fmt"
24 | "syscall"
25 | "unsafe"
26 | )
27 |
28 | // char* rustdemo(char* name);
29 |
30 | func main() {
31 | dllPath := "rustdemo.dll"
32 | rustdemo := syscall.NewLazyDLL(dllPath).NewProc("rustdemo")
33 | name := "golang"
34 | name_byte_ptr, err := syscall.BytePtrFromString(name)
35 | if err != nil {
36 | panic(err)
37 | }
38 | result_ptr, _, _ := rustdemo.Call(uintptr(unsafe.Pointer(name_byte_ptr)))
39 | // result := readCByte(result_ptr)
40 | // fmt.Printf("result: %s\n", result)
41 | result := C.GoString((*C.char)(unsafe.Pointer(result_ptr)))
42 | fmt.Printf("result: %s\n", result)
43 | }
44 |
45 |
46 | func readCByte(ptr uintptr) []byte {
47 | var result []byte
48 | for {
49 | b := (*byte)(unsafe.Pointer(ptr))
50 | if *b == 0 {
51 | break
52 | }
53 | result = append(result, *b)
54 | ptr++
55 | }
56 | return result
57 | }
58 |
59 | */
60 |
--------------------------------------------------------------------------------
/猜数游戏/src/main.rs:
--------------------------------------------------------------------------------
1 | use rand::Rng;
2 | use std::io::Write; //io::stdout().flush() 是Write trait的一个方法,所以需要导入
3 | fn main() {
4 | println!("猜数游戏!!!");
5 | let secret_number = rand::thread_rng().gen_range(1..=100);
6 | // println!("秘密数字是:{}", secret_number);
7 | let mut guess = String::new();
8 |
9 | loop {
10 | print!("猜一个数:");
11 | // 默认情况下stdout通常是行缓冲的,因此可能需要使用io::stdout().flush()以确保输出到达终端。
12 | std::io::stdout().flush().unwrap(); // 刷新缓冲区
13 |
14 | guess.clear();
15 | std::io::stdin().read_line(&mut guess).expect("读取行失败");
16 | // parse 返回一个 Result 类型,它是一个枚举,它的成员是 Ok 或 Err。
17 | let guess: i32 = match guess.trim().parse() {
18 | Ok(num) => num,
19 | Err(e) => {
20 | println!("{} 不是一个数字: {}", guess.trim(), e);
21 | continue;
22 | }
23 | };
24 | println!("你猜的数是:{} ", guess);
25 | match guess.cmp(&secret_number) {
26 | std::cmp::Ordering::Less => println!("Too small!"),
27 | std::cmp::Ordering::Greater => println!("Too big!"),
28 | std::cmp::Ordering::Equal => {
29 | println!("\x1b[1;32mYou win!\x1b[0m");
30 | break;
31 | }
32 | }
33 | println!();
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/实现一个简单的redis/tokio_hello/examples/main1.rs:
--------------------------------------------------------------------------------
1 | use std::sync::{Arc, Mutex};
2 | use tokio::task;
3 |
4 | /*
5 | https://users.rust-lang.org/t/how-to-handle-deterministic-but-not-static-lifetime-in-tokio/112089/3
6 | https://github.com/tokio-rs/tokio/issues/3162#issuecomment-2134405903
7 |
8 |
9 | tokio::spawn 要求闭包是 'static 的,这意味着闭包不能借用任何生命周期短于 'static 的数据。
10 | 这是因为 spawned 任务可能会在创建它的函数返回后继续执行,因此任何非 'static 的引用都可能变得无效。
11 |
12 | 然而,有几种方法可以解决这个问题,允许你在 Tokio 任务中使用非 'static 数据:
13 |
14 | 1. 使用 Arc 和 Mutex/RwLock (推荐)
15 |
16 | 这是最常见的也是最推荐的方法。将数据包装在 Arc> 或 Arc> 中,然后克隆 Arc 并将其移动到闭包中。
17 |
18 | 2. 在tokio外开一个新线程,使用thread::scope
19 |
20 | 3. 使用tokio::task::unconstrained,放弃异步阻塞当前线程直到任务完成
21 |
22 | 4. clone
23 | */
24 |
25 | #[tokio::main]
26 | async fn main() {
27 | let data = vec![1, 2, 3];
28 | let shared_data = Arc::new(Mutex::new(data));
29 |
30 | let handle = task::spawn({
31 | let shared_data = shared_data.clone(); // Clone the Arc
32 | async move {
33 | let mut data = shared_data.lock().unwrap();
34 | data.push(4);
35 | println!("Data inside task: {:?}", data);
36 | }
37 | });
38 |
39 | // ... Do other work ...
40 |
41 | handle.await.unwrap();
42 | println!("Final data: {:?}", shared_data.lock().unwrap());
43 | }
44 |
--------------------------------------------------------------------------------
/并发编程/examples/alternate2.rs:
--------------------------------------------------------------------------------
1 | use std::sync::mpsc;
2 |
3 | fn worker(sender: mpsc::SyncSender, receiver: UnsafeRef>, id: i32) {
4 | loop {
5 | let i = receiver.recv().unwrap();
6 | println!("worker {}: {}", id, i);
7 | sender.send(i + 1).unwrap();
8 | }
9 | }
10 |
11 | // unsafe实现,去除receiver加的锁
12 | fn main() {
13 | let (tx, rx) = mpsc::sync_channel(0);
14 | let rx = UnsafeRef::new(&rx);
15 | std::thread::scope(|s| {
16 | {
17 | let tx = tx.clone();
18 | let rx = rx.clone();
19 | s.spawn(|| worker(tx, rx, 1));
20 | }
21 | tx.send(0).unwrap();
22 | worker(tx, rx, 2);
23 | });
24 | }
25 |
26 | struct UnsafeRef {
27 | inner: *const T,
28 | }
29 |
30 | impl UnsafeRef {
31 | fn new(inner: *const T) -> Self {
32 | Self { inner }
33 | }
34 | }
35 |
36 | impl Clone for UnsafeRef {
37 | fn clone(&self) -> Self {
38 | Self { inner: self.inner }
39 | }
40 | }
41 | impl std::ops::Deref for UnsafeRef {
42 | type Target = T;
43 | fn deref(&self) -> &Self::Target {
44 | unsafe { &*self.inner }
45 | }
46 | }
47 |
48 | unsafe impl std::marker::Sync for UnsafeRef {}
49 | unsafe impl std::marker::Send for UnsafeRef {}
50 |
--------------------------------------------------------------------------------
/实现一个简单的redis/tokio_协作式调度/examples/example1.rs:
--------------------------------------------------------------------------------
1 | fn main() {
2 | let rt = tokio::runtime::Builder::new_multi_thread()
3 | .worker_threads(1)
4 | .enable_all()
5 | .build()
6 | .unwrap();
7 |
8 | let j1 = rt.spawn(async {
9 | other_worker().await;
10 | });
11 |
12 | println!("main: other_worker spawned");
13 |
14 | rt.spawn(async {
15 | http_task().await;
16 | });
17 | println!("main: http_task spawned");
18 |
19 | rt.block_on(j1).unwrap();
20 | }
21 |
22 | async fn other_worker() {
23 | let mut counter = 0;
24 | loop {
25 | counter += 1;
26 | println!("otherWorker: {}", counter);
27 | tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
28 | }
29 | }
30 |
31 | async fn http_task() {
32 | let mut counter = 0;
33 | while counter < 1000000000 {
34 | counter += 1;
35 | if counter % 50000000 == 0 {
36 | println!("httpTask: {}", counter);
37 | }
38 | }
39 | println!("httpTask: try to get http://www.baidu.com");
40 | tokio::time::sleep(tokio::time::Duration::from_secs(3)).await;
41 | println!("httpTask: get success,begin to parse html");
42 | tokio::time::sleep(tokio::time::Duration::from_secs(3)).await;
43 | println!("httpTask: done");
44 | }
45 |
--------------------------------------------------------------------------------
/并发编程/examples/barrier.rs:
--------------------------------------------------------------------------------
1 | use std::sync::{Arc, Barrier, Mutex};
2 |
3 | // Barrier 可以用 wait 来控制 n 个线程的同步,数量需要提前指明。
4 | // 当调用 wait 时,如果不是 n 个都完成,就会一直阻塞当前线程,直到第 n 个 wait 调用,才能进行后续操作。
5 | // 这种机制就像在多个线程中插入了一道屏障,当所有线程都执行到这里时,才能解除屏障继续向后执行。
6 | // 这样实现在线程数量大的时候是会有比较明显的性能开销的,底层是使用 condvar+mutex 来实现的。
7 |
8 | fn main() {
9 | let numthreads = 10;
10 | let my_mutex = Arc::new(Mutex::new(0));
11 |
12 | // We use a barrier to ensure the readout happens after all writing
13 | let barrier = Arc::new(Barrier::new(numthreads + 1));
14 |
15 | for i in 0..numthreads {
16 | let my_barrier = barrier.clone();
17 | let my_lock = my_mutex.clone();
18 | std::thread::spawn(move || {
19 | let mut guard = my_lock.lock().unwrap();
20 | *guard += 1;
21 |
22 | // Release the lock to prevent a deadlock
23 | drop(guard);
24 | println!("thread {} is ready", i);
25 | // Blocks the current thread until all threads have rendezvoused here.
26 | my_barrier.wait();
27 | println!("thread {} is done", i)
28 | });
29 | }
30 |
31 | // A barrier will block `n`-1 threads which call [`wait()`] and then wake
32 | // up all threads at once when the `n`th thread calls [`wait()`].
33 | barrier.wait();
34 |
35 | let answer = { *my_mutex.lock().unwrap() };
36 | assert_eq!(answer, numthreads);
37 | }
38 |
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "learning_materials"
3 | version = "0.1.0"
4 | edition = "2024"
5 |
6 | [dependencies]
7 |
8 |
9 | [workspace]
10 | members = [
11 | "bytes",
12 | "c调用rust",
13 | "hello_macro",
14 | "linked_list",
15 | "minigrep",
16 | "rust_golang_ffi_demo/rustdemo",
17 | "rust调用c",
18 | "sayhello_lib",
19 | "study_test",
20 | "timer_future",
21 | "unsafe_rust",
22 | "world_hello",
23 | "world_hello2",
24 | "基本数据类型",
25 | "复合类型",
26 | "宏编程",
27 | "并发编程",
28 | "异步编程",
29 | "循环引用与自引用",
30 | "所有权和借用",
31 | "文件操作",
32 | "方法_泛型_特征",
33 | "日志与监控",
34 | "智能指针",
35 | # "构建脚本/链接系统库",
36 | # "构建脚本/hello",
37 | # "构建脚本/条件编译",
38 | # "mytest",
39 | "模式匹配",
40 | "流程控制",
41 | "猜数游戏",
42 | "生命周期",
43 | "配置文件",
44 | "错误处理与格式化输出",
45 | "实现一个简单的redis/hello-my-redis",
46 | "实现一个简单的redis/mini_redis",
47 | "实现一个简单的redis/my-redis-共享状态",
48 | "实现一个简单的redis/my-redis-stream",
49 | "实现一个简单的redis/tokio_协作式调度",
50 | "实现一个简单的redis/tokio_异步跟同步共存",
51 | "实现一个简单的redis/tokio_异步原理",
52 | "实现一个简单的redis/tokio_优雅的关闭",
53 | "实现一个简单的redis/tokio_hello",
54 | "实现一个简单的redis/tokio_select",
55 | "实现一个简单的redis/tokio_stream",
56 | "实现一个简单的redis/tokio_tcp",
57 | "web服务器/单线程版本的_web_服务器",
58 | "web服务器/实践多线程_web服务器",
59 | "web服务器/异步_web服务器",
60 | "web服务器/异步多线程_web服务器",
61 | ]
62 |
--------------------------------------------------------------------------------
/hello_macro/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "hello_macro"
7 | version = "0.1.0"
8 | dependencies = [
9 | "hello_macro_derive",
10 | "syn",
11 | ]
12 |
13 | [[package]]
14 | name = "hello_macro_derive"
15 | version = "0.1.0"
16 | dependencies = [
17 | "quote",
18 | "syn",
19 | ]
20 |
21 | [[package]]
22 | name = "proc-macro2"
23 | version = "1.0.67"
24 | source = "registry+https://github.com/rust-lang/crates.io-index"
25 | checksum = "3d433d9f1a3e8c1263d9456598b16fec66f4acc9a74dacffd35c7bb09b3a1328"
26 | dependencies = [
27 | "unicode-ident",
28 | ]
29 |
30 | [[package]]
31 | name = "quote"
32 | version = "1.0.33"
33 | source = "registry+https://github.com/rust-lang/crates.io-index"
34 | checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae"
35 | dependencies = [
36 | "proc-macro2",
37 | ]
38 |
39 | [[package]]
40 | name = "syn"
41 | version = "2.0.37"
42 | source = "registry+https://github.com/rust-lang/crates.io-index"
43 | checksum = "7303ef2c05cd654186cb250d29049a24840ca25d2747c25c0381c8d9e2f582e8"
44 | dependencies = [
45 | "proc-macro2",
46 | "quote",
47 | "unicode-ident",
48 | ]
49 |
50 | [[package]]
51 | name = "unicode-ident"
52 | version = "1.0.8"
53 | source = "registry+https://github.com/rust-lang/crates.io-index"
54 | checksum = "e5464a87b239f13a63a501f2701565754bae92d243d4bb7eb12f6d57d2269bf4"
55 |
--------------------------------------------------------------------------------
/实现一个简单的redis/my-redis-stream/src/bin/client.rs:
--------------------------------------------------------------------------------
1 | use mini_redis::client;
2 | use tokio_stream::StreamExt;
3 |
4 | async fn publish() -> mini_redis::Result<()> {
5 | let mut client = client::connect("127.0.0.1:6379").await?;
6 |
7 | // 发布一些数据
8 | client.publish("numbers", "1".into()).await?;
9 | client.publish("numbers", "two".into()).await?;
10 | client.publish("numbers", "3".into()).await?;
11 | client.publish("numbers", "four".into()).await?;
12 | client.publish("numbers", "five".into()).await?;
13 | client.publish("numbers", "6".into()).await?;
14 | Ok(())
15 | }
16 |
17 | async fn subscribe() -> mini_redis::Result<()> {
18 | let client = client::connect("127.0.0.1:6379").await?;
19 | let subscriber = client.subscribe(vec!["numbers".to_string()]).await?;
20 | // into_stream 会将 `Subscriber` 变成一个 `stream`
21 | let messages = subscriber.into_stream();
22 |
23 | tokio::pin!(messages);
24 |
25 | while let Some(msg) = messages.next().await {
26 | println!("got = {:?}", msg);
27 | }
28 |
29 | Ok(())
30 | }
31 |
32 | // 上面生成了一个异步任务专门用于发布消息到 min-redis 服务器端的 `numbers` 消息通道中。
33 | // 然后,在 `main` 中,我们订阅了 `numbers` 消息通道,并且打印从中接收到的消息。
34 |
35 | // 先运行mini-redis服务器
36 | // $mini-redis-server
37 | #[tokio::main]
38 | async fn main() -> mini_redis::Result<()> {
39 | tokio::spawn(async { publish().await });
40 |
41 | subscribe().await?;
42 |
43 | println!("DONE");
44 |
45 | Ok(())
46 | }
47 |
--------------------------------------------------------------------------------
/日志与监控/examples/main1.rs:
--------------------------------------------------------------------------------
1 | use log::{Level, debug, error, info, log_enabled, trace, warn};
2 |
3 | pub fn shave_the_yak(yak: &mut Yak) {
4 | trace!("Commencing yak shaving");
5 |
6 | loop {
7 | match find_a_razor() {
8 | Ok(razor) => {
9 | info!("Razor located: {:?}", razor);
10 | yak.shave(razor);
11 | break;
12 | }
13 | Err(err) => {
14 | warn!("Unable to locate a razor: {}, retrying", err);
15 | }
16 | }
17 | std::thread::sleep(std::time::Duration::from_secs(1));
18 | }
19 | }
20 |
21 | pub struct Yak {
22 | name: String,
23 | }
24 |
25 | impl Yak {
26 | pub fn shave(&mut self, razor: Razor) {
27 | println!("Shaving yak {:?} with {:?}", self.name, razor);
28 | }
29 | }
30 | #[derive(Debug)]
31 | pub struct Razor;
32 |
33 | fn find_a_razor() -> Result {
34 | Err("Could not find a razor".to_string())
35 | }
36 |
37 | fn main() {
38 | env_logger::builder()
39 | .filter_level(log::LevelFilter::Trace)
40 | .init();
41 | debug!("this is a debug {}", "message");
42 | error!("this is printed by default");
43 |
44 | if log_enabled!(Level::Info) {
45 | let x = 3 * 4; // expensive computation
46 | info!("the answer was: {}", x);
47 | }
48 | let mut yak = Yak {
49 | name: "Fred".to_string(),
50 | };
51 | shave_the_yak(&mut yak);
52 | }
53 |
--------------------------------------------------------------------------------
/实现一个简单的redis/hello-my-redis/examples/hello-redis.rs:
--------------------------------------------------------------------------------
1 | use mini_redis::{Result, client};
2 |
3 | // 在代码中,使用了一个与众不同的 main 函数 : async fn main ,
4 | // 而且是用 #[tokio::main] 属性进行了标记。异步 main 函数有以下意义:
5 |
6 | // .await 只能在 async 函数中使用,如果是以前的 fn main,
7 | // 那它内部是无法直接使用 async 函数的!这个会极大的限制了我们的使用场景
8 | // 异步运行时本身需要初始化
9 |
10 | // `#[tokio::main]` 宏在将 `async fn main` 隐式的转换为 `fn main` 的同时
11 | // 还对整个异步运行时进行了初始化。例如以下代码:
12 | /*
13 |
14 | #[tokio::main]
15 | async fn main() {
16 | println!("hello");
17 | }
18 |
19 | 将被转换成:
20 | fn main() {
21 | let mut rt = tokio::runtime::Runtime::new().unwrap();
22 | rt.block_on(async {
23 | println!("hello");
24 | })
25 | }
26 |
27 | */
28 |
29 | #[tokio::main]
30 | async fn main() -> Result<()> {
31 | // 建立与mini-redis服务器的连接
32 | // >$ mini-redis-server
33 | let mut client = client::connect("127.0.0.1:6379").await?;
34 |
35 | // 设置 key: "hello" 和 值: "world"
36 | client.set("hello", "world".into()).await?;
37 |
38 | // 获取"key=hello"的值
39 | let result = client.get("hello").await?;
40 |
41 | println!("从服务器端获取到结果={:?}", result);
42 |
43 | async fn say_to_world() -> String {
44 | String::from("world")
45 | }
46 |
47 | // 此处的函数调用是惰性的,并不会执行 say_to_world() 函数体中的代码
48 | let op = say_to_world();
49 |
50 | // 首先打印出 "hello"
51 | println!("hello");
52 |
53 | // 使用 .await 让 say_to_world 开始运行起来
54 | // async fn 到底返回什么?它实际上返回的是一个实现了 Future 特征的匿名类型:
55 | // impl Future