mirror of
https://github.com/gnu4cn/rust-lang-zh_CN.git
synced 2025-01-13 22:00:50 +08:00
reorganized the directories
This commit is contained in:
parent
a957d08fd7
commit
2aaae6f4d2
6
projects/add/Cargo.toml
Normal file
6
projects/add/Cargo.toml
Normal file
@ -0,0 +1,6 @@
|
||||
[workspace]
|
||||
|
||||
members = [
|
||||
"adder",
|
||||
"add_one",
|
||||
]
|
9
projects/add/add_one/Cargo.toml
Normal file
9
projects/add/add_one/Cargo.toml
Normal file
@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "add_one"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
rand = "^0.8.4"
|
14
projects/add/add_one/src/lib.rs
Normal file
14
projects/add/add_one/src/lib.rs
Normal file
@ -0,0 +1,14 @@
|
||||
pub fn add_one(x: i32) -> i32 {
|
||||
x + 1
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn it_works() {
|
||||
let result = add_one(2);
|
||||
assert_eq!(result, 3);
|
||||
}
|
||||
}
|
10
projects/add/adder/Cargo.toml
Normal file
10
projects/add/adder/Cargo.toml
Normal file
@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "adder"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
add_one = { path = "../add_one" }
|
||||
rand = "0.8.4"
|
6
projects/add/adder/src/main.rs
Normal file
6
projects/add/adder/src/main.rs
Normal file
@ -0,0 +1,6 @@
|
||||
use add_one::add_one;
|
||||
|
||||
fn main() {
|
||||
let num = 10;
|
||||
println!("你好,世界!\n\t{num} 加 1 为 {}!", add_one(num));
|
||||
}
|
8
projects/adder/Cargo.toml
Normal file
8
projects/adder/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "adder"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
17
projects/adder/src/lib.rs
Normal file
17
projects/adder/src/lib.rs
Normal file
@ -0,0 +1,17 @@
|
||||
pub fn add_two(a: i32) -> i32 {
|
||||
internal_add(a, 2)
|
||||
}
|
||||
|
||||
fn internal_add(a: i32, b: i32) -> i32 {
|
||||
a + b
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn internal() {
|
||||
assert_eq! (4, internal_add(2, 2));
|
||||
}
|
||||
}
|
3
projects/adder/tests/common/mod.rs
Normal file
3
projects/adder/tests/common/mod.rs
Normal file
@ -0,0 +1,3 @@
|
||||
pub fn setup() {
|
||||
println! ("特定于库测试的一些设置代码,将放在这里");
|
||||
}
|
9
projects/adder/tests/integration_test.rs
Normal file
9
projects/adder/tests/integration_test.rs
Normal file
@ -0,0 +1,9 @@
|
||||
use adder;
|
||||
|
||||
mod common;
|
||||
|
||||
#[test]
|
||||
fn it_adds_two() {
|
||||
common::setup();
|
||||
assert_eq! (6, adder::add_two(4));
|
||||
}
|
8
projects/aggregator/Cargo.toml
Normal file
8
projects/aggregator/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "aggregator"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
3
projects/aggregator/src/bin/test_case.rs
Normal file
3
projects/aggregator/src/bin/test_case.rs
Normal file
@ -0,0 +1,3 @@
|
||||
fn main() {
|
||||
println! ("媒体聚合器");
|
||||
}
|
56
projects/aggregator/src/lib.rs
Normal file
56
projects/aggregator/src/lib.rs
Normal file
@ -0,0 +1,56 @@
|
||||
pub trait Summary {
|
||||
fn summarize_author(&self) -> String;
|
||||
|
||||
fn summarize(&self) -> String {
|
||||
format! ("(了解更多来自 {} ......)", self.summarize_author())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NewsArticle {
|
||||
pub headline: String,
|
||||
pub location: String,
|
||||
pub author: String,
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
impl Summary for NewsArticle {
|
||||
fn summarize_author(&self) -> String {
|
||||
format! ("{}", self.author)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Tweet {
|
||||
pub username: String,
|
||||
pub content: String,
|
||||
pub reply: bool,
|
||||
pub retweet: bool,
|
||||
}
|
||||
|
||||
impl Summary for Tweet {
|
||||
fn summarize_author(&self) -> String {
|
||||
format! ("@{}", self.username)
|
||||
}
|
||||
}
|
||||
|
||||
use std::fmt::Display;
|
||||
|
||||
pub struct Pair<T> {
|
||||
pub x: T,
|
||||
pub y: T,
|
||||
}
|
||||
|
||||
impl<T> Pair<T> {
|
||||
pub fn new(x: T, y: T) -> Self {
|
||||
Self { x, y }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Display + PartialOrd> Pair<T> {
|
||||
pub fn cmp_display(&self) {
|
||||
if self.x >= self.y {
|
||||
println! ("极大数为 x = {}", self.x);
|
||||
} else {
|
||||
println! ("极大数为 y = {}", self.y);
|
||||
}
|
||||
}
|
||||
}
|
54
projects/aggregator/src/main.rs
Normal file
54
projects/aggregator/src/main.rs
Normal file
@ -0,0 +1,54 @@
|
||||
use aggregator::{Summary, Tweet, NewsArticle, Pair};
|
||||
|
||||
pub fn notify<T: Summary>(item: &T) {
|
||||
println! ("突发新闻!{}", item.summarize());
|
||||
}
|
||||
|
||||
fn return_summarizable() -> impl Summary {
|
||||
Tweet {
|
||||
username: String::from("horse_ebooks"),
|
||||
content: String::from(
|
||||
"当然,如同你或许已经知道的一样,朋友们"
|
||||
),
|
||||
reply: false,
|
||||
retweet: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let tweet = Tweet {
|
||||
username: String::from("horse_ebooks"),
|
||||
content: String::from(
|
||||
"当然,跟大家已经清楚的一样了,朋友们",
|
||||
),
|
||||
reply: false,
|
||||
retweet: false,
|
||||
};
|
||||
|
||||
println!("1 条新推文: {}", tweet.summarize());
|
||||
notify(&tweet);
|
||||
|
||||
|
||||
let article = NewsArticle {
|
||||
headline: String::from("企鹅队赢得斯坦利杯锦标赛!"),
|
||||
location: String::from("美国,宾夕法尼亚州,匹兹堡"),
|
||||
author: String::from("Iceburgh"),
|
||||
content: String::from(
|
||||
"匹兹堡企鹅队再度成为美国曲棍球联盟 \
|
||||
NHL 中的最佳球队。"
|
||||
),
|
||||
};
|
||||
|
||||
println! ("有新文章可读!{}", article.summarize());
|
||||
notify(&article);
|
||||
|
||||
println! ("1 条旧推文: {}", return_summarizable().summarize());
|
||||
|
||||
let pair = Pair::new(5, 10);
|
||||
pair.cmp_display();
|
||||
|
||||
let pair = Pair::new("这是一个测试", "This is a test.");
|
||||
pair.cmp_display();
|
||||
|
||||
println! ("{}", 3.to_string());
|
||||
}
|
8
projects/art/Cargo.toml
Normal file
8
projects/art/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "art"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
15
projects/art/src/kinds.rs
Normal file
15
projects/art/src/kinds.rs
Normal file
@ -0,0 +1,15 @@
|
||||
/// RYB 颜色模型下的主要颜色。
|
||||
#[derive(Debug)]
|
||||
pub enum PrimaryColor {
|
||||
Red,
|
||||
Yellow,
|
||||
Blue,
|
||||
}
|
||||
|
||||
/// RYB 颜色模型下的次要颜色。
|
||||
#[derive(Debug)]
|
||||
pub enum SecondaryColor {
|
||||
Orange,
|
||||
Green,
|
||||
Purple,
|
||||
}
|
10
projects/art/src/lib.rs
Normal file
10
projects/art/src/lib.rs
Normal file
@ -0,0 +1,10 @@
|
||||
//! # art - 美术
|
||||
//!
|
||||
//! 建模诸多美术概念的一个库。
|
||||
|
||||
pub mod kinds;
|
||||
pub mod utils;
|
||||
|
||||
pub use self::kinds::PrimaryColor;
|
||||
pub use self::kinds::SecondaryColor;
|
||||
pub use self::utils::mix;
|
9
projects/art/src/utils.rs
Normal file
9
projects/art/src/utils.rs
Normal file
@ -0,0 +1,9 @@
|
||||
use crate::kinds::*;
|
||||
|
||||
/// 结合两种等量的主要颜色,创建出
|
||||
/// 某种次要颜色。
|
||||
pub fn mix(c1: PrimaryColor, c2: PrimaryColor) -> SecondaryColor {
|
||||
// --跳过代码--
|
||||
println! ("c1: {:?}, c2: {:?}", c1, c2);
|
||||
SecondaryColor::Purple
|
||||
}
|
8
projects/assert_demo/Cargo.toml
Normal file
8
projects/assert_demo/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "assert_demo"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
43
projects/assert_demo/src/lib.rs
Normal file
43
projects/assert_demo/src/lib.rs
Normal file
@ -0,0 +1,43 @@
|
||||
pub fn add_two(a: i32) -> i32 {
|
||||
a + 2
|
||||
}
|
||||
|
||||
pub fn nth_fibonacci(n: u64) -> u64 {
|
||||
|
||||
if n == 0 || n == 1 {
|
||||
return n;
|
||||
} else {
|
||||
return nth_fibonacci(n - 1) + nth_fibonacci(n - 2);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn add_two_and_two() {
|
||||
assert_eq! (4, add_two(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_three_and_two() {
|
||||
assert_eq! (5, add_two(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_hundred() {
|
||||
assert_eq! (102, add_two(100));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_works() {
|
||||
assert_eq! (2 + 2, 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn expensive_test() {
|
||||
assert_ne! (100, nth_fibonacci(50));
|
||||
}
|
||||
}
|
8
projects/associated_type/Cargo.toml
Normal file
8
projects/associated_type/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "associated_type"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
3
projects/associated_type/src/main.rs
Normal file
3
projects/associated_type/src/main.rs
Normal file
@ -0,0 +1,3 @@
|
||||
fn main() {
|
||||
println!("Hello, world!");
|
||||
}
|
8
projects/branches/Cargo.toml
Normal file
8
projects/branches/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "branches"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
7
projects/branches/src/main.rs
Normal file
7
projects/branches/src/main.rs
Normal file
@ -0,0 +1,7 @@
|
||||
fn main() {
|
||||
let condition = true;
|
||||
|
||||
let number = if condition { 5 } else { "six" };
|
||||
|
||||
println! ("number 的值为:{}", number);
|
||||
}
|
9
projects/cargo_features_demo/Cargo.toml
Normal file
9
projects/cargo_features_demo/Cargo.toml
Normal file
@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "cargo_features_demo"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
art = { path = "../art" }
|
21
projects/cargo_features_demo/src/lib.rs
Normal file
21
projects/cargo_features_demo/src/lib.rs
Normal file
@ -0,0 +1,21 @@
|
||||
//! # Cargo 特性示例代码箱
|
||||
//!
|
||||
//! `cargo_features_demo` 是令到执行某些确切计算更便利
|
||||
//! 的一些工具的集合。
|
||||
//!
|
||||
|
||||
/// 将一加到所给数字。
|
||||
/// # 示例(examples)
|
||||
///
|
||||
/// ```
|
||||
/// let arg = 5;
|
||||
/// let answer = cargo_features_demo::add_one(arg);
|
||||
///
|
||||
/// assert_eq! (6, answer);
|
||||
/// ```
|
||||
pub fn add_one(x: i32) -> i32 {
|
||||
x + 2
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
8
projects/cargo_features_demo/src/main.rs
Normal file
8
projects/cargo_features_demo/src/main.rs
Normal file
@ -0,0 +1,8 @@
|
||||
use art::mix;
|
||||
use art::PrimaryColor;
|
||||
|
||||
fn main() {
|
||||
let red = PrimaryColor::Red;
|
||||
let yellow = PrimaryColor::Yellow;
|
||||
mix(red, yellow);
|
||||
}
|
6
projects/cargo_features_demo/src/tests.rs
Normal file
6
projects/cargo_features_demo/src/tests.rs
Normal file
@ -0,0 +1,6 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn five_plus_one() {
|
||||
assert_eq! (7, add_one(5));
|
||||
}
|
8
projects/clippy_demo/Cargo.toml
Normal file
8
projects/clippy_demo/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "clippy_demo"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
5
projects/clippy_demo/src/main.rs
Normal file
5
projects/clippy_demo/src/main.rs
Normal file
@ -0,0 +1,5 @@
|
||||
fn main() {
|
||||
let x = std::f64::consts::PI;
|
||||
let r = 8.0;
|
||||
println!("圆的面积为 {}", x * r * r);
|
||||
}
|
8
projects/closure-example/Cargo.toml
Normal file
8
projects/closure-example/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "closure-example"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
22
projects/closure-example/src/main.rs
Normal file
22
projects/closure-example/src/main.rs
Normal file
@ -0,0 +1,22 @@
|
||||
#[derive(Debug)]
|
||||
struct Rectangle {
|
||||
width: u32,
|
||||
height: u32,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut list = [
|
||||
Rectangle { width: 10, height: 1 },
|
||||
Rectangle { width: 3, height: 5 },
|
||||
Rectangle { width: 7, height: 12 },
|
||||
];
|
||||
|
||||
let mut sort_operations = vec! [];
|
||||
let value = String::from("按照被调用到的 key");
|
||||
|
||||
list.sort_by_key(|r| {
|
||||
sort_operations.push(&value);
|
||||
r.width
|
||||
});
|
||||
println! ("{:#?}\n{:#?}", list, sort_operations);
|
||||
}
|
8
projects/closure_demo/Cargo.toml
Normal file
8
projects/closure_demo/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "closure_demo"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
57
projects/closure_demo/src/main.rs
Normal file
57
projects/closure_demo/src/main.rs
Normal file
@ -0,0 +1,57 @@
|
||||
#[derive(Debug, PartialEq, Copy, Clone)]
|
||||
enum ShirtColor {
|
||||
Red,
|
||||
Blue,
|
||||
}
|
||||
|
||||
struct Inventory {
|
||||
shirts: Vec<ShirtColor>,
|
||||
}
|
||||
|
||||
impl Inventory {
|
||||
fn giveaway(
|
||||
&self,
|
||||
user_preference: Option<ShirtColor>
|
||||
) -> ShirtColor {
|
||||
user_preference.unwrap_or_else(|| self.most_stocked())
|
||||
}
|
||||
|
||||
fn most_stocked(&self) -> ShirtColor {
|
||||
let mut num_red = 0;
|
||||
let mut num_blue = 0;
|
||||
|
||||
for color in &self.shirts {
|
||||
match color {
|
||||
ShirtColor::Red => num_red += 1,
|
||||
ShirtColor::Blue => num_blue += 1,
|
||||
}
|
||||
}
|
||||
|
||||
if num_red > num_blue {
|
||||
ShirtColor::Red
|
||||
} else {
|
||||
ShirtColor::Blue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let store = Inventory {
|
||||
shirts: vec! [ShirtColor::Blue, ShirtColor::Red, ShirtColor::Blue],
|
||||
};
|
||||
|
||||
let user_pref1 = Some(ShirtColor::Red);
|
||||
let giveaway1 = store.giveaway(user_pref1);
|
||||
println! (
|
||||
"选项为 {:?} 的用户,得到了 {:?}",
|
||||
user_pref1, giveaway1
|
||||
);
|
||||
|
||||
let user_pref2 = None;
|
||||
let giveaway2 = store.giveaway(user_pref2);
|
||||
println! (
|
||||
"选项为 {:?} 的用户得到了 {:?}",
|
||||
user_pref2, giveaway2
|
||||
);
|
||||
|
||||
}
|
8
projects/concur_demo/Cargo.toml
Normal file
8
projects/concur_demo/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "concur_demo"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
14
projects/concur_demo/src/main.rs
Normal file
14
projects/concur_demo/src/main.rs
Normal file
@ -0,0 +1,14 @@
|
||||
#![allow(dead_code)]
|
||||
#![allow(unused_variables)]
|
||||
|
||||
use std::thread;
|
||||
|
||||
fn main() {
|
||||
let v = vec! [1, 2, 3];
|
||||
|
||||
let handle = thread::spawn(move || {
|
||||
println! ("这里有个矢量值:{:?}", &v);
|
||||
});
|
||||
|
||||
handle.join().unwrap();
|
||||
}
|
8
projects/cons_list_demo/Cargo.toml
Normal file
8
projects/cons_list_demo/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "cons_list_demo"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
24
projects/cons_list_demo/src/main.rs
Normal file
24
projects/cons_list_demo/src/main.rs
Normal file
@ -0,0 +1,24 @@
|
||||
#[derive(Debug)]
|
||||
enum List {
|
||||
Cons(Rc<RefCell<i32>>, Rc<List>),
|
||||
Nil,
|
||||
}
|
||||
|
||||
use crate::List::{Cons, Nil};
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
fn main() {
|
||||
let value = Rc::new(RefCell::new(5));
|
||||
|
||||
let a = Rc::new(Cons(Rc::clone(&value), Rc::new(Nil)));
|
||||
|
||||
let b = Cons(Rc::new(RefCell::new(3)), Rc::clone(&a));
|
||||
let c = Cons(Rc::new(RefCell::new(4)), Rc::clone(&a));
|
||||
|
||||
*value.borrow_mut() += 10;
|
||||
|
||||
println! ("之后的 a = {:?}", a);
|
||||
println! ("之后的 b = {:?}", b);
|
||||
println! ("之后的 c = {:?}", c);
|
||||
}
|
8
projects/declarative_macro/Cargo.toml
Normal file
8
projects/declarative_macro/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "declarative_macro"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
4
projects/declarative_macro/src/main.rs
Normal file
4
projects/declarative_macro/src/main.rs
Normal file
@ -0,0 +1,4 @@
|
||||
fn main() {
|
||||
|
||||
println!("Hello, world!");
|
||||
}
|
10
projects/derive_macro_comsumer/Cargo.toml
Normal file
10
projects/derive_macro_comsumer/Cargo.toml
Normal file
@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "derive_macro_comsumer"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
hello_macro = { path = "../hello_macro" }
|
||||
hello_macro_derive = { path = "../hello_macro/hello_macro_derive" }
|
9
projects/derive_macro_comsumer/src/main.rs
Normal file
9
projects/derive_macro_comsumer/src/main.rs
Normal file
@ -0,0 +1,9 @@
|
||||
use hello_macro::HelloMacro;
|
||||
use hello_macro_derive::HelloMacro;
|
||||
|
||||
#[derive(HelloMacro)]
|
||||
struct Pancakes;
|
||||
|
||||
fn main() {
|
||||
Pancakes::hello_macro();
|
||||
}
|
8
projects/disambiguation/Cargo.toml
Normal file
8
projects/disambiguation/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "disambiguation"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
21
projects/disambiguation/src/main.rs
Normal file
21
projects/disambiguation/src/main.rs
Normal file
@ -0,0 +1,21 @@
|
||||
trait Animal {
|
||||
fn baby_name() -> String;
|
||||
}
|
||||
|
||||
struct Dog;
|
||||
|
||||
impl Dog {
|
||||
fn baby_name() -> String {
|
||||
String::from("点点")
|
||||
}
|
||||
}
|
||||
|
||||
impl Animal for Dog {
|
||||
fn baby_name() -> String {
|
||||
String::from("狗崽")
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println! ("小狗叫做 {}", <Dog as Animal>::baby_name());
|
||||
}
|
8
projects/dst/Cargo.toml
Normal file
8
projects/dst/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "dst"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
4
projects/dst/src/main.rs
Normal file
4
projects/dst/src/main.rs
Normal file
@ -0,0 +1,4 @@
|
||||
fn main() {
|
||||
let s1: str = "致以问候!";
|
||||
let s2: str = "最近过得怎么样?";
|
||||
}
|
8
projects/encapsulation_demo/Cargo.toml
Normal file
8
projects/encapsulation_demo/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "encapsulation_demo"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
34
projects/encapsulation_demo/src/lib.rs
Normal file
34
projects/encapsulation_demo/src/lib.rs
Normal file
@ -0,0 +1,34 @@
|
||||
#![allow(dead_code)]
|
||||
#![allow(unused_variables)]
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
8
projects/enum_demo/Cargo.toml
Normal file
8
projects/enum_demo/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "enum_demo"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
7
projects/enum_demo/src/main.rs
Normal file
7
projects/enum_demo/src/main.rs
Normal file
@ -0,0 +1,7 @@
|
||||
fn main() {
|
||||
let config_max: Option<u8> = Some(3u8);
|
||||
|
||||
if let Option::Some(max) = (config_max) {
|
||||
println! ("极大值被设置为了 {}", max);
|
||||
}
|
||||
}
|
8
projects/error_handling_demo/Cargo.toml
Normal file
8
projects/error_handling_demo/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "error_handling_demo"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
9
projects/error_handling_demo/src/main.rs
Normal file
9
projects/error_handling_demo/src/main.rs
Normal file
@ -0,0 +1,9 @@
|
||||
fn main () {
|
||||
use std::net::IpAddr;
|
||||
|
||||
let home: IpAddr = "192.168.0.255"
|
||||
.parse()
|
||||
.expect("硬编码的 IP 地址应是有效的");
|
||||
|
||||
println! ("{}", home);
|
||||
}
|
8
projects/extern_code/Cargo.toml
Normal file
8
projects/extern_code/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "extern_code"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
17
projects/extern_code/src/main.rs
Normal file
17
projects/extern_code/src/main.rs
Normal file
@ -0,0 +1,17 @@
|
||||
extern "C" {
|
||||
fn abs(input: i32) -> i32;
|
||||
fn sqrt(input: f64) -> f64;
|
||||
}
|
||||
|
||||
|
||||
#[no_mangle]
|
||||
pub extern "C" fn call_from_c() {
|
||||
println! ("刚从 C 调用了一个 Rust 函数!");
|
||||
}
|
||||
|
||||
fn main() {
|
||||
unsafe {
|
||||
println! ("C 语言中 -3 的绝对值为:{},3.0 的平方根为:{}", abs(-3), sqrt(3.0));
|
||||
}
|
||||
}
|
||||
|
8
projects/fah_to_cels/Cargo.toml
Normal file
8
projects/fah_to_cels/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "fah_to_cels"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
67
projects/fah_to_cels/src/main.rs
Normal file
67
projects/fah_to_cels/src/main.rs
Normal file
@ -0,0 +1,67 @@
|
||||
use std::io;
|
||||
use std::process;
|
||||
|
||||
fn fah_to_cels(f: f32) -> f32 {
|
||||
return (f - 32.0) / 1.8;
|
||||
}
|
||||
|
||||
fn cels_to_fah(c: f32) -> f32 {
|
||||
return c * 1.8 + 32.0;
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println! ("法式温度与摄氏温度之间的转换");
|
||||
|
||||
loop {
|
||||
println! ("\n-----------------\n请选择:
|
||||
'1'-摄氏温度/'2'-法式温度/'Q'/\"quit\" 退出程序。
|
||||
'1'/'2'/'Q'/\"quit\"[1]:");
|
||||
|
||||
let mut temp_type = String::new();
|
||||
|
||||
io::stdin()
|
||||
.read_line(&mut temp_type)
|
||||
.expect("读取输入失败!");
|
||||
|
||||
let temp_type = temp_type.trim();
|
||||
|
||||
if temp_type.eq("Q") || temp_type.eq("quit") { process::exit(0); }
|
||||
|
||||
if ! temp_type.eq("1") && ! temp_type.eq("2") && ! temp_type.eq("") {
|
||||
println! ("无效输入,请输入 '1'、'2'、'Q'、\"quit\",或直接按下回车键");
|
||||
continue;
|
||||
}
|
||||
|
||||
if temp_type.eq("1") || temp_type.eq("") {
|
||||
println! ("请输入要转换的摄氏温度:");
|
||||
let temp = get_temp_input();
|
||||
|
||||
println! ("摄氏温度: {:.2}°C,约为法氏温度:{:.2}°F", temp, cels_to_fah(temp));
|
||||
}
|
||||
|
||||
if temp_type.eq("2") {
|
||||
println! ("请输入要转换的法氏温度:");
|
||||
let temp = get_temp_input();
|
||||
|
||||
println! ("法氏温度:{:.2}°F,约为摄氏温度:{:.2}°C", temp, fah_to_cels(temp));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn get_temp_input() -> f32 {
|
||||
return loop {
|
||||
let mut tmp = String::new();
|
||||
|
||||
io::stdin()
|
||||
.read_line(&mut tmp)
|
||||
.expect("读取输入失败");
|
||||
|
||||
match tmp.trim().parse() {
|
||||
Ok(num) => { break num },
|
||||
Err(_) => {
|
||||
println! ("请输入一个浮点数,比如 -10.0, 15.6");
|
||||
continue
|
||||
}
|
||||
};
|
||||
};
|
||||
}
|
8
projects/fn_pattn_demo/Cargo.toml
Normal file
8
projects/fn_pattn_demo/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "fn_pattn_demo"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
8
projects/fn_pattn_demo/src/main.rs
Normal file
8
projects/fn_pattn_demo/src/main.rs
Normal file
@ -0,0 +1,8 @@
|
||||
fn print_coordinates(&(x, y): &(i32, i32)) {
|
||||
println!("当前坐标:({}, {})", x, y);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let point = (3, -5);
|
||||
print_coordinates(&point);
|
||||
}
|
8
projects/for_demo/Cargo.toml
Normal file
8
projects/for_demo/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "for_demo"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
7
projects/for_demo/src/main.rs
Normal file
7
projects/for_demo/src/main.rs
Normal file
@ -0,0 +1,7 @@
|
||||
fn main() {
|
||||
let v = vec! ['a', 'b', 'c'];
|
||||
|
||||
for (index, value) in v.iter().enumerate() {
|
||||
println! ("{} 处于索引 {} 处", value, index);
|
||||
}
|
||||
}
|
8
projects/func_pointer/Cargo.toml
Normal file
8
projects/func_pointer/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "func_pointer"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
30
projects/func_pointer/src/main.rs
Normal file
30
projects/func_pointer/src/main.rs
Normal file
@ -0,0 +1,30 @@
|
||||
fn add_one(x: i32) -> i32 {
|
||||
x + 1
|
||||
}
|
||||
|
||||
fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 {
|
||||
f(arg) + f(arg)
|
||||
}
|
||||
|
||||
|
||||
fn main() {
|
||||
let answer = do_twice(add_one, 5);
|
||||
|
||||
println! ("答案为:{}", answer);
|
||||
|
||||
let list_of_numbers = vec! [1, 2, 3];
|
||||
let list_of_strings: Vec<String> =
|
||||
list_of_numbers.iter().map(ToString::to_string).collect();
|
||||
|
||||
println! ("结果为:{:?}", list_of_strings);
|
||||
|
||||
#[derive(Debug)]
|
||||
enum Status {
|
||||
Value(u32),
|
||||
Stop,
|
||||
}
|
||||
|
||||
let mut list_of_statuses: Vec<Status> = (0u32..20).map(Status::Value).collect();
|
||||
list_of_statuses.append(&mut vec! [Status::Stop]);
|
||||
println! ("list_of_statuses: {:?}", list_of_statuses);
|
||||
}
|
8
projects/functions/Cargo.toml
Normal file
8
projects/functions/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "functions"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
9
projects/functions/src/main.rs
Normal file
9
projects/functions/src/main.rs
Normal file
@ -0,0 +1,9 @@
|
||||
fn main() {
|
||||
let x = plus_one(-1);
|
||||
|
||||
println! ("x 的值为:{}", x);
|
||||
}
|
||||
|
||||
fn plus_one(x: i32) -> i32 {
|
||||
x + 1
|
||||
}
|
8
projects/generics_demo/Cargo.toml
Normal file
8
projects/generics_demo/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "generics_demo"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
14
projects/generics_demo/src/main.rs
Normal file
14
projects/generics_demo/src/main.rs
Normal file
@ -0,0 +1,14 @@
|
||||
enum Option_i32 {
|
||||
Some(i32),
|
||||
None,
|
||||
}
|
||||
|
||||
enum Option_f64 {
|
||||
Some(f64),
|
||||
None,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let integer = Option_i32::Some(5);
|
||||
let float = Option_f64::Some(5.0);
|
||||
}
|
11
projects/guessing_game/Cargo.toml
Normal file
11
projects/guessing_game/Cargo.toml
Normal file
@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "guessing_game-xfossdotcom"
|
||||
license = "MIT"
|
||||
version = "0.1.1"
|
||||
description = "一个在其中猜出计算机所选数字的有趣游戏。"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
rand = "0.8.3"
|
3
projects/guessing_game/README.md
Normal file
3
projects/guessing_game/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
# Readme
|
||||
|
||||
这是一个作为把代码箱上传到 [crates.io](https://crates.io) 示例的 Rust 项目。
|
64
projects/guessing_game/src/main.rs
Normal file
64
projects/guessing_game/src/main.rs
Normal file
@ -0,0 +1,64 @@
|
||||
use rand::Rng;
|
||||
use std::{cmp::Ordering, io, process};
|
||||
|
||||
pub struct Guess {
|
||||
value: i32,
|
||||
}
|
||||
|
||||
impl Guess {
|
||||
pub fn new(value: i32) -> Guess {
|
||||
if value < 1 || value > 100 {
|
||||
panic! ("Guess 类型值必须在 1 与 100 之间,收到的是 {}", value);
|
||||
}
|
||||
|
||||
Guess { value }
|
||||
}
|
||||
|
||||
pub fn value(&self) -> i32 {
|
||||
self.value
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
loop {
|
||||
println! ("\n---猜出这个数来!---");
|
||||
|
||||
let secret_number: i32 = rand::thread_rng().gen_range(1..101);
|
||||
|
||||
// println! ("随机生成的秘密数字为:{}", secret_number);
|
||||
|
||||
loop {
|
||||
println! ("请输入你猜的数。( ‘Q/quit’ 退出游戏)");
|
||||
|
||||
let mut guess: String = String::new();
|
||||
|
||||
io::stdin()
|
||||
.read_line(&mut guess)
|
||||
.expect("读取行失败......");
|
||||
|
||||
if guess.trim().eq("Q") || guess.trim().eq("quit") { process::exit(0); }
|
||||
|
||||
// let guess: u32 = guess.trim().parse().expect("请输入一个数字!");
|
||||
let guess: i32 = match guess.trim().parse() {
|
||||
Ok(num) => num,
|
||||
Err(_) => { println! ("请输入一个数字!"); continue },
|
||||
};
|
||||
|
||||
if guess < 1 || guess > 100 {
|
||||
println! ("秘密数字将在 1 和 100 之间");
|
||||
continue
|
||||
}
|
||||
|
||||
println! ("你猜的数为:{}", guess);
|
||||
|
||||
match guess.cmp(&secret_number) {
|
||||
Ordering::Less => println! ("太小了!"),
|
||||
Ordering::Greater => println! ("太大了!"),
|
||||
Ordering::Equal => {
|
||||
println! ("你赢了!");
|
||||
break
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
8
projects/hashmap_demo/Cargo.toml
Normal file
8
projects/hashmap_demo/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "hashmap_demo"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
14
projects/hashmap_demo/src/main.rs
Normal file
14
projects/hashmap_demo/src/main.rs
Normal file
@ -0,0 +1,14 @@
|
||||
fn main() {
|
||||
use std::collections::HashMap;
|
||||
|
||||
let text = "hello world wonderful world";
|
||||
|
||||
let mut map = HashMap::new();
|
||||
|
||||
for word in text.split_whitespace() {
|
||||
let count = map.entry(word).or_insert(0);
|
||||
*count += 1;
|
||||
}
|
||||
|
||||
println! ("{:?}", map);
|
||||
}
|
11
projects/hello/404.html
Normal file
11
projects/hello/404.html
Normal file
@ -0,0 +1,11 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>你好!</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>糟糕!</h1>
|
||||
<p>抱歉,我不明白你要什么。</p>
|
||||
</body>
|
||||
</html>
|
8
projects/hello/Cargo.toml
Normal file
8
projects/hello/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "hello"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
11
projects/hello/hello.html
Normal file
11
projects/hello/hello.html
Normal file
@ -0,0 +1,11 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>你好!</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>你好!</h1>
|
||||
<p>来自 Rust 的问好</p>
|
||||
</body>
|
||||
</html>
|
92
projects/hello/src/lib.rs
Normal file
92
projects/hello/src/lib.rs
Normal file
@ -0,0 +1,92 @@
|
||||
use std::{
|
||||
sync::{mpsc, Arc, Mutex},
|
||||
thread,
|
||||
};
|
||||
|
||||
pub struct ThreadPool {
|
||||
workers: Vec<Worker>,
|
||||
sender: Option<mpsc::Sender<Job>>,
|
||||
}
|
||||
|
||||
type Job = Box<dyn FnOnce() + Send + 'static>;
|
||||
|
||||
impl ThreadPool {
|
||||
/// 创建出一个新的 ThreadPool。
|
||||
///
|
||||
/// 其中的 size 为线程池中线程的数目。
|
||||
///
|
||||
/// # 终止运行
|
||||
///
|
||||
/// 这个 `new` 函数将在 size 为零时终止运行。
|
||||
pub fn new(size: usize) -> ThreadPool {
|
||||
assert! (size > 0);
|
||||
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
|
||||
let receiver = Arc::new(Mutex::new(receiver));
|
||||
|
||||
let mut workers = Vec::with_capacity(size);
|
||||
|
||||
for id in 0..size {
|
||||
workers.push(Worker::new(id, Arc::clone(&receiver)));
|
||||
}
|
||||
|
||||
ThreadPool {
|
||||
workers,
|
||||
sender: Some(sender),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn execute<F>(&self, f: F)
|
||||
where
|
||||
F: FnOnce() + Send + 'static,
|
||||
{
|
||||
let job = Box::new(f);
|
||||
|
||||
self.sender.as_ref().unwrap().send(job).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ThreadPool {
|
||||
fn drop(&mut self) {
|
||||
drop(self.sender.take());
|
||||
|
||||
for worker in &mut self.workers {
|
||||
println! ("关闭 worker {}", worker.id);
|
||||
|
||||
if let Some(thread) = worker.thread.take() {
|
||||
thread.join().unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Worker {
|
||||
id: usize,
|
||||
thread: Option<thread::JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl Worker {
|
||||
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
|
||||
let thread = thread::spawn(move || loop {
|
||||
let message = receiver.lock().unwrap().recv();
|
||||
|
||||
match message {
|
||||
Ok(job) => {
|
||||
println! ("Worker {id} 获取到一项作业;执行中。");
|
||||
|
||||
job();
|
||||
}
|
||||
Err(_) => {
|
||||
println! ("Worker {id} 已断开链接;关闭中。");
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Worker {
|
||||
id,
|
||||
thread: Some(thread),
|
||||
}
|
||||
}
|
||||
}
|
46
projects/hello/src/main.rs
Normal file
46
projects/hello/src/main.rs
Normal file
@ -0,0 +1,46 @@
|
||||
use hello::ThreadPool;
|
||||
|
||||
use std::{
|
||||
fs,
|
||||
thread,
|
||||
io::{prelude::*, BufReader},
|
||||
net::{TcpListener, TcpStream},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
fn main() {
|
||||
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
|
||||
let pool = ThreadPool::new(4);
|
||||
|
||||
for stream in listener.incoming().take(2) {
|
||||
let stream = stream.unwrap();
|
||||
|
||||
pool.execute(|| {
|
||||
handle_conn(stream);
|
||||
});
|
||||
}
|
||||
|
||||
println! ("关闭中。");
|
||||
}
|
||||
|
||||
fn handle_conn(mut stream: TcpStream) {
|
||||
let buf_reader = BufReader::new(&mut stream);
|
||||
let req_line = buf_reader.lines().next().unwrap().unwrap();
|
||||
|
||||
let (status_line, filename) = match &req_line[..] {
|
||||
"GET / HTTP/1.1" => ( "HTTP/1.1 200 OK", "hello.html"),
|
||||
"GET /sleep HTTP/1.1" => {
|
||||
thread::sleep(Duration::from_secs(10));
|
||||
("HTTP/1.1 200 0K", "hello.html")
|
||||
}
|
||||
_ => ("HTTP/1.1 404 NOT FOUND", "404.html"),
|
||||
};
|
||||
|
||||
let contents = fs::read_to_string(filename).unwrap();
|
||||
let length = contents.len();
|
||||
|
||||
let resp =
|
||||
format! ("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
|
||||
|
||||
stream.write_all(resp.as_bytes()).unwrap();
|
||||
}
|
8
projects/hello_cargo/Cargo.toml
Normal file
8
projects/hello_cargo/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "hello_cargo"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
4
projects/hello_cargo/src/main.rs
Normal file
4
projects/hello_cargo/src/main.rs
Normal file
@ -0,0 +1,4 @@
|
||||
fn main() {
|
||||
// 这是注释。
|
||||
println! ("Hello, Cargo!");
|
||||
}
|
8
projects/hello_macro/Cargo.toml
Normal file
8
projects/hello_macro/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "hello_macro"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
12
projects/hello_macro/hello_macro_derive/Cargo.toml
Normal file
12
projects/hello_macro/hello_macro_derive/Cargo.toml
Normal file
@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "hello_macro_derive"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
syn = "1.0"
|
||||
quote = "1.0"
|
26
projects/hello_macro/hello_macro_derive/src/lib.rs
Normal file
26
projects/hello_macro/hello_macro_derive/src/lib.rs
Normal file
@ -0,0 +1,26 @@
|
||||
use proc_macro::TokenStream;
|
||||
use quote::quote;
|
||||
use syn;
|
||||
|
||||
#[proc_macro_derive(HelloMacro)]
|
||||
pub fn hello_macro_derive(input: TokenStream) -> TokenStream {
|
||||
// 以语法树形式,构建出咱们可操作 Rust 代码的表示
|
||||
// Construct a representation of Rust code as a syntax tree
|
||||
// that we can manipulate
|
||||
let ast = syn::parse(input).unwrap();
|
||||
|
||||
// 构造出这个特质实现
|
||||
impl_hello_macro(&ast)
|
||||
}
|
||||
|
||||
fn impl_hello_macro(ast: &syn::DeriveInput) -> TokenStream {
|
||||
let name = &ast.ident;
|
||||
let gen = quote! {
|
||||
impl HelloMacro for #name {
|
||||
fn hello_macro() {
|
||||
println! ("你好,宏!我的名字叫 {}!", stringify! (#name));
|
||||
}
|
||||
}
|
||||
};
|
||||
gen.into()
|
||||
}
|
3
projects/hello_macro/src/lib.rs
Normal file
3
projects/hello_macro/src/lib.rs
Normal file
@ -0,0 +1,3 @@
|
||||
pub trait HelloMacro {
|
||||
fn hello_macro();
|
||||
}
|
8
projects/hello_macro_derive/Cargo.toml
Normal file
8
projects/hello_macro_derive/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "hello_macro_derive"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
14
projects/hello_macro_derive/src/lib.rs
Normal file
14
projects/hello_macro_derive/src/lib.rs
Normal file
@ -0,0 +1,14 @@
|
||||
pub fn add(left: usize, right: usize) -> usize {
|
||||
left + right
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn it_works() {
|
||||
let result = add(2, 2);
|
||||
assert_eq!(result, 4);
|
||||
}
|
||||
}
|
8
projects/hello_world/Cargo.toml
Normal file
8
projects/hello_world/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "hello_world"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
4
projects/hello_world/src/main.rs
Normal file
4
projects/hello_world/src/main.rs
Normal file
@ -0,0 +1,4 @@
|
||||
fn main() {
|
||||
// 这是注释。
|
||||
println!("Hello, World!");
|
||||
}
|
8
projects/if_let_demo/Cargo.toml
Normal file
8
projects/if_let_demo/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "if_let_demo"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
22
projects/if_let_demo/src/main.rs
Normal file
22
projects/if_let_demo/src/main.rs
Normal file
@ -0,0 +1,22 @@
|
||||
#![allow(dead_code)]
|
||||
#![allow(unused_variables)]
|
||||
|
||||
fn main() {
|
||||
let favorite_color: Option<&str> = None;
|
||||
let is_tuesday = false;
|
||||
let age: Result<u8, _> = "34".parse();
|
||||
|
||||
if let Some(color) = favorite_color {
|
||||
println! ("使用你喜欢的颜色,{color},作为背景");
|
||||
} else if is_tuesday {
|
||||
println! ("周二是绿色的一天!");
|
||||
} else if let Ok(age) = age {
|
||||
if age > 30 {
|
||||
println! ("使用紫色作为背景色");
|
||||
} else {
|
||||
println! ("使用橙色作为背景色");
|
||||
}
|
||||
} else {
|
||||
println! ("使用蓝色作为背景色");
|
||||
}
|
||||
}
|
8
projects/iterator_demo/Cargo.toml
Normal file
8
projects/iterator_demo/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "iterator_demo"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
35
projects/iterator_demo/src/lib.rs
Normal file
35
projects/iterator_demo/src/lib.rs
Normal file
@ -0,0 +1,35 @@
|
||||
#[derive(PartialEq, Debug)]
|
||||
struct Shoe {
|
||||
size: u32,
|
||||
style: String,
|
||||
}
|
||||
|
||||
fn shoes_in_size(shoes: Vec<Shoe>, shoe_size: u32) -> Vec<Shoe> {
|
||||
shoes.into_iter().filter(|s| s.size == shoe_size).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
#[test]
|
||||
fn iterator_demonstration() {
|
||||
let v1 = vec! [1, 2, 3];
|
||||
|
||||
let mut v1_iter = v1.iter();
|
||||
|
||||
assert_eq! (v1_iter.next(), Some(&1));
|
||||
assert_eq! (v1_iter.next(), Some(&2));
|
||||
assert_eq! (v1_iter.next(), Some(&3));
|
||||
assert_eq! (v1_iter.next(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iterator_sum() {
|
||||
let v1 = vec! [1, 2, 3];
|
||||
|
||||
let v1_iter = v1.iter();
|
||||
|
||||
let total: i32 = v1_iter.sum();
|
||||
|
||||
assert_eq! (total, 6);
|
||||
}
|
7
projects/iterator_demo/src/main.rs
Normal file
7
projects/iterator_demo/src/main.rs
Normal file
@ -0,0 +1,7 @@
|
||||
fn main() {
|
||||
let v1 = vec! [1, 2, 3];
|
||||
|
||||
let v2: Vec<_> = v1.iter().map(|x| x + 1).collect();
|
||||
|
||||
assert_eq! (v2, vec! [2, 3, 4]);
|
||||
}
|
35
projects/iterator_demo/src/tests.rs
Normal file
35
projects/iterator_demo/src/tests.rs
Normal file
@ -0,0 +1,35 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn filter_by_size() {
|
||||
let shoes = vec! [
|
||||
Shoe {
|
||||
size: 10,
|
||||
style: String::from("sneaker"),
|
||||
},
|
||||
Shoe {
|
||||
size: 13,
|
||||
style: String::from("sandal"),
|
||||
},
|
||||
Shoe {
|
||||
size: 10,
|
||||
style: String::from("boot"),
|
||||
},
|
||||
];
|
||||
|
||||
let in_my_size = shoes_in_size(shoes, 10);
|
||||
|
||||
assert_eq! (
|
||||
in_my_size,
|
||||
vec! [
|
||||
Shoe {
|
||||
size: 10,
|
||||
style: String::from("sneaker"),
|
||||
},
|
||||
Shoe {
|
||||
size: 10,
|
||||
style: String::from("boot"),
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
8
projects/lifetimes_demo/Cargo.toml
Normal file
8
projects/lifetimes_demo/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "lifetimes_demo"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
23
projects/lifetimes_demo/src/main.rs
Normal file
23
projects/lifetimes_demo/src/main.rs
Normal file
@ -0,0 +1,23 @@
|
||||
use std::fmt::Display;
|
||||
|
||||
fn longest_with_an_announcement<'a, T>(
|
||||
x: &'a str,
|
||||
y: &'a str,
|
||||
ann: T,
|
||||
) -> &'a str
|
||||
where
|
||||
T: Display,
|
||||
{
|
||||
println! ("通知!{}", ann);
|
||||
if x.len() > y.len() {
|
||||
x
|
||||
} else {
|
||||
y
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let result = longest_with_an_announcement("abc", "测试", "计算结果已出来。");
|
||||
|
||||
println! ("{}", result);
|
||||
}
|
8
projects/limit_tracker/Cargo.toml
Normal file
8
projects/limit_tracker/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "limit_tracker"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
77
projects/limit_tracker/src/lib.rs
Normal file
77
projects/limit_tracker/src/lib.rs
Normal file
@ -0,0 +1,77 @@
|
||||
pub trait Messenger {
|
||||
fn send(&self, msg: &str);
|
||||
}
|
||||
|
||||
pub struct LimitTracker<'a, T: Messenger> {
|
||||
messenger: &'a T,
|
||||
value: usize,
|
||||
max: usize,
|
||||
}
|
||||
|
||||
impl<'a, T> LimitTracker<'a, T>
|
||||
where
|
||||
T: Messenger,
|
||||
{
|
||||
pub fn new(messenger: &'a T, max: usize) -> LimitTracker<'a, T> {
|
||||
LimitTracker {
|
||||
messenger,
|
||||
value: 0,
|
||||
max,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_value(&mut self, value: usize) {
|
||||
self.value = value;
|
||||
|
||||
let percentage_of_max = self.value as f64 / self.max as f64;
|
||||
|
||||
if percentage_of_max >= 1.0 {
|
||||
self.messenger.send("出错:你已超出你的配额!");
|
||||
} else if percentage_of_max >= 0.9 {
|
||||
self.messenger
|
||||
.send("紧急警告:你已用掉你配额的 90% !");
|
||||
} else if percentage_of_max >= 0.75 {
|
||||
self.messenger
|
||||
.send("警告:你已用掉你配额的 75% !");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::RefCell;
|
||||
|
||||
struct MockMessenger {
|
||||
sent_messages: RefCell<Vec<String>>,
|
||||
}
|
||||
|
||||
impl MockMessenger {
|
||||
fn new() -> MockMessenger {
|
||||
MockMessenger {
|
||||
sent_messages: RefCell::new(vec! []),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Messenger for MockMessenger {
|
||||
fn send(&self, message: &str) {
|
||||
let mut borrow_one = self.sent_messages.borrow_mut();
|
||||
let mut borrow_two = self.sent_messages.borrow_mut();
|
||||
|
||||
borrow_one.push(String::from(message));
|
||||
borrow_two.push(String::from(message));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_sends_an_over_75_percent_waring_message() {
|
||||
let mock_messenger = MockMessenger::new();
|
||||
let mut limit_tracker = LimitTracker::new(&mock_messenger, 100);
|
||||
|
||||
limit_tracker.set_value(80);
|
||||
println! ("{}", mock_messenger.sent_messages.borrow().iter().next().unwrap());
|
||||
|
||||
assert_eq! (mock_messenger.sent_messages.borrow().len(), 1);
|
||||
}
|
||||
}
|
8
projects/loops/Cargo.toml
Normal file
8
projects/loops/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "loops"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
7
projects/loops/src/main.rs
Normal file
7
projects/loops/src/main.rs
Normal file
@ -0,0 +1,7 @@
|
||||
fn main() {
|
||||
for number in (1..4).rev() {
|
||||
println! ("{}!", number);
|
||||
}
|
||||
|
||||
println! ("发射!!");
|
||||
}
|
8
projects/lyrics_of_xmas_carol/Cargo.toml
Normal file
8
projects/lyrics_of_xmas_carol/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "lyrics_of_xmas_carol"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
60
projects/lyrics_of_xmas_carol/src/main.rs
Normal file
60
projects/lyrics_of_xmas_carol/src/main.rs
Normal file
@ -0,0 +1,60 @@
|
||||
fn main() {
|
||||
let days = [
|
||||
"first",
|
||||
"second",
|
||||
"third",
|
||||
"fourth",
|
||||
"fifth",
|
||||
"sixth",
|
||||
"seventh",
|
||||
"eighth",
|
||||
"nineth",
|
||||
"tenth",
|
||||
"eleventh",
|
||||
"twelfth"
|
||||
];
|
||||
let amounts = [
|
||||
"A",
|
||||
"Two",
|
||||
"Three",
|
||||
"Four",
|
||||
"Five",
|
||||
"Six",
|
||||
"Seven",
|
||||
"Eight",
|
||||
"Nine",
|
||||
"Ten",
|
||||
"Eleven",
|
||||
"Twelve"
|
||||
];
|
||||
let things = [
|
||||
"partridge in a pear tree",
|
||||
"turtle doves",
|
||||
"French hens",
|
||||
"calling birds",
|
||||
"golden rings",
|
||||
"geese-a-laying",
|
||||
"swans-a-swimming",
|
||||
"maids-a-milking",
|
||||
"ladies dancing",
|
||||
"lords-a-leaping",
|
||||
"pipers piping",
|
||||
"drummers drumming",
|
||||
];
|
||||
|
||||
for num in 1..=12 {
|
||||
println! ("\nOn the {} day of Christmas,\nMy true love gave to me:",
|
||||
days[num-1]);
|
||||
for tmp in (0..num).rev() {
|
||||
if tmp == 0 && num == 1 {
|
||||
println! ("{} {}.", amounts[tmp], things[tmp]);
|
||||
}
|
||||
if tmp == 0 && num != 1 {
|
||||
println! ("And {} {}.", amounts[tmp].to_lowercase(), things[tmp]);
|
||||
}
|
||||
if tmp != 0 {
|
||||
println! ("{} {},", amounts[tmp], things[tmp]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
14
projects/minigrep/Cargo.toml
Normal file
14
projects/minigrep/Cargo.toml
Normal file
@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "minigrep"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
|
||||
[profile.dev]
|
||||
opt-level = 1
|
||||
|
||||
[profile.release]
|
||||
opt-level = 3
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user