DAILY DOCDAILY DOC
Rust
Node
Notes
Ubuntu
Leetcode
  • it-tools
  • excalidraw
  • linux-command
Rust
Node
Notes
Ubuntu
Leetcode
  • it-tools
  • excalidraw
  • linux-command
  • rust

    • Rust
    • add
    • 属性(attributes)
    • cargo issue
    • cli
    • build.rs
    • Enums
    • eventEmitter(rust)
    • 格式化输出 std::fmt
    • rust iterator
    • rust 学习计划
    • 生命周期(lifetime)
    • Linked List
    • log
    • macros
    • mem::size_of
    • niche optimization
    • Rust 所有权
    • 模式匹配(pattern matching)
    • module system
    • result & option
    • .rust-analyzer.json
    • rust startup
    • rust-test
    • 可见性(visibility)
    • cargo
    • toml

rust 学习计划

阶段一:基础阶段(1-2周)

学习目标

  • 掌握Rust的基础语法
  • 熟悉Rust的编译和运行环境

学习内容

  1. 环境搭建

    • 安装Rust工具链:rustup、cargo
    • 设置开发环境(推荐VSCode + Rust扩展)
  2. 基础语法

    • 变量与常量
    • 数据类型
    • 函数
    • 控制流(条件语句、循环)
  3. 所有权与借用

    • 所有权规则
    • 引用与借用
    • 生命周期
  4. 结构体与枚举

    • 定义与使用结构体
    • 定义与使用枚举
    • 模式匹配
  5. 集合类型

    • 数组与切片
    • Vector
    • HashMap
  6. 基本错误处理

    • Result与Option类型
    • 错误传播

1. 环境搭建

  • 安装Rust工具链:rustup、cargo
  • 设置开发环境(推荐VSCode + Rust扩展)

安装Rust:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

更新Rust工具链:

rustup update

创建一个新项目:

cargo new hello_world
cd hello_world

编译和运行项目:

cargo build
cargo run

2. 基础语法

变量与常量:

fn main() {
    let mut x = 5;
    println!("The value of x is: {}", x);
    x = 6;
    println!("The value of x is: {}", x);

    const MAX_POINTS: u32 = 100_000;
    println!("The max points are: {}", MAX_POINTS);
}

数据类型:

fn main() {
    let guess: u32 = "42".parse().expect("Not a number!");
    let x = 2.0; // f64
    let y: f32 = 3.0; // f32

    let sum = 5 + 10;
    let difference = 95.5 - 4.3;
    let product = 4 * 30;
    let quotient = 56.7 / 32.2;
    let remainder = 43 % 5;

    println!("sum: {}, difference: {}, product: {}, quotient: {}, remainder: {}", sum, difference, product, quotient, remainder);
}

函数:

fn main() {
    println!("Hello, world!");

    another_function(5);
}

fn another_function(x: i32) {
    println!("The value of x is: {}", x);
}

控制流:

fn main() {
    let number = 6;

    if number % 4 == 0 {
        println!("number is divisible by 4");
    } else if number % 3 == 0 {
        println!("number is divisible by 3");
    } else if number % 2 == 0 {
        println!("number is divisible by 2");
    } else {
        println!("number is not divisible by 4, 3, or 2");
    }

    let mut count = 0;
    while count != 5 {
        println!("count is: {}", count);
        count += 1;
    }

    for number in (1..4).rev() {
        println!("{}!", number);
    }
    println!("LIFTOFF!!!");
}

3. 所有权与借用

所有权规则:

fn main() {
    let s1 = String::from("hello");
    let s2 = s1;
    // println!("{}", s1); // 这里会报错,因为s1的所有权已经转移给了s2

    let s1 = String::from("hello");
    let s2 = s1.clone();
    println!("s1 = {}, s2 = {}", s1, s2); // 这里可以正常运行,因为s1被克隆了
}

引用与借用:

fn main() {
    let s1 = String::from("hello");
    let len = calculate_length(&s1);
    println!("The length of '{}' is {}.", s1, len);
}

fn calculate_length(s: &String) -> usize {
    s.len()
}

生命周期:

fn main() {
    let r;
    {
        let x = 5;
        r = &x;
    }
    // println!("r: {}", r); // 这里会报错,因为x在离开作用域后被销毁
}

4. 结构体与枚举

定义与使用结构体:

struct User {
    username: String,
    email: String,
    sign_in_count: u64,
    active: bool,
}

fn main() {
    let user1 = User {
        email: String::from("someone@example.com"),
        username: String::from("someusername123"),
        active: true,
        sign_in_count: 1,
    };

    println!("Username: {}", user1.username);
}

定义与使用枚举:

enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

fn main() {
    let msg = Message::Write(String::from("hello"));
    match msg {
        Message::Quit => println!("Quit message"),
        Message::Move { x, y } => println!("Move message to x: {}, y: {}", x, y),
        Message::Write(text) => println!("Write message: {}", text),
        Message::ChangeColor(r, g, b) => println!("Change color to r: {}, g: {}, b: {}", r, g, b),
    }
}

5. 集合类型

数组与切片:

fn main() {
    let a = [1, 2, 3, 4, 5];
    let first = a[0];
    let second = a[1];
    println!("First element: {}, Second element: {}", first, second);

    let s = &a[1..3];
    println!("Slice: {:?}", s);
}

Vector:

fn main() {
    let mut v: Vec<i32> = Vec::new();
    v.push(5);
    v.push(6);
    v.push(7);
    v.push(8);

    let third: &i32 = &v[2];
    println!("The third element is {}", third);

    match v.get(2) {
        Some(third) => println!("The third element is {}", third),
        None => println!("There is no third element."),
    }
}

HashMap:

use std::collections::HashMap;

fn main() {
    let mut scores = HashMap::new();
    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);

    let team_name = String::from("Blue");
    let score = scores.get(&team_name);
    println!("The score for team Blue is {:?}", score);

    for (key, value) in &scores {
        println!("{}: {}", key, value);
    }
}

6. 基本错误处理

Result与Option类型:

use std::fs::File;
use std::io::ErrorKind;

fn main() {
    let f = File::open("hello.txt");

    let f = match f {
        Ok(file) => file,
        Err(ref error) if error.kind() == ErrorKind::NotFound => {
            match File::create("hello.txt") {
                Ok(fc) => fc,
                Err(e) => panic!("Problem creating the file: {:?}", e),
            }
        },
        Err(error) => {
            panic!("Problem opening the file: {:?}", error);
        },
    };
}

继续基础阶段的学习内容,将包括更多的代码示例和解释,以确保对Rust的基础知识有更全面的理解。

7. 额外的基础内容

字符串处理:

fn main() {
    // 字符串切片
    let s = String::from("hello world");
    let hello = &s[0..5];
    let world = &s[6..11];
    println!("{} {}", hello, world);

    // 字符串连接
    let s1 = String::from("Hello, ");
    let s2 = String::from("world!");
    let s3 = s1 + &s2; // 注意s1已经被移动,不能再使用
    println!("{}", s3);

    // 格式化字符串
    let s1 = String::from("tic");
    let s2 = String::from("tac");
    let s3 = String::from("toe");
    let s = format!("{}-{}-{}", s1, s2, s3);
    println!("{}", s);
}

切片类型:

fn main() {
    let a = [1, 2, 3, 4, 5];

    let slice = &a[1..3];
    assert_eq!(slice, &[2, 3]);

    println!("Slice: {:?}", slice);
}

简单CLI应用程序:

use std::env;

fn main() {
    let args: Vec<String> = env::args().collect();
    let query = &args[1];
    let filename = &args[2];

    println!("Searching for {}", query);
    println!("In file {}", filename);
}

处理错误:

use std::fs::File;
use std::io::{self, Read};

fn read_username_from_file() -> Result<String, io::Error> {
    let mut s = String::new();
    File::open("hello.txt")?.read_to_string(&mut s)?;
    Ok(s)
}

fn main() {
    match read_username_from_file() {
        Ok(username) => println!("Username: {}", username),
        Err(e) => println!("Error reading file: {:?}", e),
    }
}

测试:

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }

    #[test]
    fn another() {
        panic!("Make this test fail");
    }
}

基础阶段的学习总结

通过上述内容的学习,应该对以下几个方面有了清晰的理解:

  1. 环境搭建与工具链使用:

    • 熟悉Rust编译器、包管理工具Cargo的使用,能够创建、编译和运行Rust项目。
  2. 基础语法:

    • 变量与常量:掌握变量的声明、可变性、常量的定义。
    • 数据类型:了解基本数据类型及其操作。
    • 函数:能够定义和调用函数,理解函数参数和返回值。
    • 控制流:掌握条件语句、循环语句的使用。
  3. 所有权与借用:

    • 深入理解所有权规则,知道如何避免所有权转移引发的错误。
    • 掌握引用与借用的使用方法,理解Rust的借用检查器。
    • 初步了解生命周期。
  4. 结构体与枚举:

    • 能够定义和使用结构体与枚举,掌握模式匹配的基本用法。
  5. 集合类型:

    • 掌握数组、切片、Vector、HashMap的使用。
  6. 基本错误处理:

    • 能够使用Result与Option类型处理错误,了解错误传播。
  7. 其他:

    • 掌握字符串处理的基本方法。
    • 了解切片类型的使用。
    • 能够编写简单的CLI应用程序。
    • 初步了解测试的编写和运行。

学习资源

  • The Rust Programming Language
  • Rust By Example

阶段二:中级阶段(2-4周)

学习目标

  • 深入理解Rust的核心概念
  • 开始编写简单的Rust项目

学习内容

  1. 模块与包

    • 创建和使用模块
    • crate与包管理
  2. 迭代器与闭包

    • 定义与使用迭代器
    • 闭包的语法与应用
  3. 错误处理

    • 自定义错误类型
    • 错误处理最佳实践
  4. 多线程编程

    • 线程的创建与管理
    • 线程安全与共享状态(Arc与Mutex)
  5. 文件与网络

    • 文件读写
    • 基本的网络编程

1. 模块与包

创建和使用模块:

// src/main.rs
mod front_of_house;

fn main() {
    front_of_house::hosting::add_to_waitlist();
}

// src/front_of_house.rs
pub mod hosting;

// src/front_of_house/hosting.rs
pub fn add_to_waitlist() {
    println!("Added to waitlist");
}

crate与包管理:

# Cargo.toml
[dependencies]
regex = "1"

# 使用外部crate
use regex::Regex;

fn main() {
    let re = Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap();
    let date = "2023-06-01";
    assert!(re.is_match(date));
    println!("Date {} matches pattern", date);
}

2. 迭代器与闭包

定义与使用迭代器:

fn main() {
    let v1 = vec![1, 2, 3];
    let v1_iter = v1.iter();

    for val in v1_iter {
        println!("Got: {}", val);
    }
}

#[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);
}

闭包的语法与应用:

fn main() {
    let add_one = |x: i32| -> i32 { x + 1 };
    assert_eq!(add_one(1), 2);

    let mut num = 5;
    {
        let mut add_num = |x: i32| num += x;
        add_num(5);
    }
    assert_eq!(num, 10);
}

3. 错误处理

自定义错误类型:

use std::fmt;

#[derive(Debug)]
struct CustomError {
    details: String,
}

impl CustomError {
    fn new(msg: &str) -> CustomError {
        CustomError{details: msg.to_string()}
    }
}

impl fmt::Display for CustomError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.details)
    }
}

impl std::error::Error for CustomError {
    fn description(&self) -> &str {
        &self.details
    }
}

fn do_something() -> Result<(), CustomError> {
    Err(CustomError::new("Something went wrong"))
}

fn main() {
    match do_something() {
        Ok(_) => println!("Success"),
        Err(e) => println!("Error: {}", e),
    }
}

4. 多线程编程

线程的创建与管理:

use std::thread;
use std::time::Duration;

fn main() {
    let handle = thread::spawn(|| {
        for i in 1..10 {
            println!("Hi number {} from the spawned thread!", i);
            thread::sleep(Duration::from_millis(1));
        }
    });

    for i in 1..5 {
        println!("Hi number {} from the main thread!", i);
        thread::sleep(Duration::from_millis(1));
    }

    handle.join().unwrap();
}

线程安全与共享状态(Arc与Mutex):

use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];

    for _ in 0..10 {
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();
            *num += 1;
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("Result: {}", *counter.lock().unwrap());
}

5. 文件与网络

文件读写:

use std::fs::File;
use std::io::{self, Read, Write};

fn main() -> io::Result<()> {
    let mut file = File::create("foo.txt")?;
    file.write_all(b"Hello, world!")?;

    let mut file = File::open("foo.txt")?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    println!("File contents: {}", contents);

    Ok(())
}

基本的网络编程:

use std::io::{Read, Write};
use std::net::TcpListener;

fn main() -> std::io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:7878")?;

    for stream in listener.incoming() {
        let mut stream = stream?;
        let mut buffer = [0; 512];
        stream.read(&mut buffer)?;
        stream.write(&buffer)?;
    }

    Ok(())
}

学习资源

  • Rust Programming by Example
  • Rust Cookbook

阶段三:高级阶段(4-6周)

学习目标

  • 掌握Rust的高级特性
  • 能够优化和调试Rust代码

学习内容

  1. 高级所有权与借用

    • 高级生命周期
    • 高级引用类型(RefCell、Rc)
  2. 宏与泛型

    • 定义与使用宏
    • 泛型编程
  3. 异步编程

    • async/await语法
    • 异步编程模型
  4. 性能优化

    • 内存管理与优化
    • 性能调优工具
  5. FFI与嵌入式开发

    • 与C语言互操作
    • 基本的嵌入式开发

1. 高级所有权与借用

高级生命周期:

fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}

fn main() {
    let string1 = String::from("long string is long");
    let result;
    {
        let string2 = String::from("xyz");
        result = longest(string1.as_str(), string2.as_str());
    }
    // println!("The longest string is {}", result); // 这里会报错,因为string2已经超出了生命周期
}

高级引用类型(RefCell、Rc):

use std::rc::Rc;
use std::cell::RefCell;

#[derive(Debug)]
struct List {
    value: i32,
    next: Option<Rc<RefCell<List>>>,
}

fn main() {
    let a = Rc::new(RefCell::new(List { value: 5, next: None }));
    let b = Rc::new(RefCell::new(List { value: 10, next: Some(Rc::clone(&a)) }));

    println!("{:?}", b);
}

2. 宏与泛型

定义与使用宏:

macro_rules! say_hello {
    () => {
        println!("Hello!");
    };
}

fn main() {
    say_hello!();
}

泛型编程:

struct Point<T> {
    x: T,
    y: T,
}

impl<T> Point<T> {
    fn new(x: T, y: T) -> Self {
        Point { x, y }
    }
}

fn main() {
    let int_point = Point::new(5, 10);
    let float_point = Point::new(1.0, 4.0);

    println!("Int point: ({}, {})", int_point.x, int_point.y);
    println!("Float point: ({}, {})", float_point.x, float_point.y);
}

3. 异步编程

async/await语法:

use tokio::time::{sleep, Duration};

async fn say_hello() {
    println!("Hello, world!");
    sleep(Duration::from_secs(1)).await;
    println!("Goodbye, world!");
}

#[tokio::main]
async fn main() {
    say_hello().await;
}

异步编程模型:

use tokio::runtime::Runtime;

fn main() {
    let rt = Runtime::new().unwrap();
    rt.block_on(async {
        let handle = tokio::spawn(async {
            println!("Hello from a new thread");
        });

        handle.await.unwrap();
    });
}

4. 性能优化

内存管理与优化:

fn main() {
    let mut data = vec![1, 2, 3, 4, 5];

    // 使用shrink_to_fit来减少内存占用
    data.shrink_to_fit();
    println!("{:?}", data);
}

#[inline(always)]
fn optimized_function() {
    // 使用#[inline(always)]来强制内联,提高性能
    println!("This is an optimized function");
}

性能调优工具:

  • Profiling工具:如cargo-profiler和flamegraph
  • Benchmarking工具:如criterion

使用Criterion进行基准测试:

use criterion::{black_box, criterion_group, criterion_main, Criterion};

fn fibonacci(n: u64) -> u64 {
    match n {
        0 => 0,
        1 => 1,
        _ => fibonacci(n - 1) + fibonacci(n - 2),
    }
}

fn criterion_benchmark(c: &mut Criterion) {
    c.bench_function("fibonacci 20", |b| b.iter(|| fibonacci(black_box(20))));
}

criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);

5. FFI与嵌入式开发

与C语言互操作:

extern "C" {
    fn abs(input: i32) -> i32;
}

fn main() {
    unsafe {
        println!("Absolute value of -3 according to C: {}", abs(-3));
    }
}

基本的嵌入式开发: 使用no_std进行嵌入式编程:

#![no_std]
#![no_main]

extern crate panic_halt;

use core::panic::PanicInfo;

#[no_mangle]
pub extern "C" fn main() -> ! {
    loop {}
}

#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
    loop {}
}

学习资源

  • Programming Rust
  • Rust Async Programming

阶段四:项目实战阶段(6周以上)

学习目标

  • 通过项目实践巩固所学知识
  • 解决实际问题,积累开发经验

学习内容

  1. 选择项目

    • Web开发(使用Rocket或Actix)
    • 系统编程(编写命令行工具)
    • 数据分析与处理
  2. 项目开发

    • 需求分析与设计
    • 编写代码与测试
    • 项目优化与发布
  3. 参与开源

    • 贡献开源项目
    • 参与Rust社区活动

详细学习内容与代码示例

1. 项目选择与规划

选择一个适合自己的项目,确保项目能够涵盖Rust的各个方面,从基础语法到高级特性。以下是几个项目建议:

  • 命令行应用程序:如一个文件管理工具或一个简单的任务管理器
  • Web应用程序:使用框架如Rocket或Actix构建一个简单的Web服务
  • 网络应用程序:如一个简单的聊天服务器或HTTP客户端
  • 系统工具:如一个内存监视工具或日志分析工具
  • 嵌入式项目:如一个简单的IoT设备控制程序

项目规划:

  1. 定义项目目标和范围
  2. 设计项目结构和模块
  3. 确定技术栈和工具
  4. 制定开发计划和时间表

2. 项目开发

以一个命令行应用程序为例,详细介绍项目开发过程。

项目结构:

my_cli_app/
├── Cargo.toml
├── src/
│   ├── main.rs
│   ├── cli.rs
│   ├── commands/
│   │   ├── mod.rs
│   │   ├── add.rs
│   │   ├── remove.rs
│   │   └── list.rs

Cargo.toml

[package]
name = "my_cli_app"
version = "0.1.0"
edition = "2021"

[dependencies]
clap = "3.0"

src/main.rs

mod cli;
mod commands;

use clap::Command;

fn main() {
    let matches = cli::build_cli().get_matches();

    if let Some(ref matches) = matches.subcommand_matches("add") {
        commands::add::execute(matches);
    } else if let Some(ref matches) = matches.subcommand_matches("remove") {
        commands::remove::execute(matches);
    } else if let Some(ref matches) = matches.subcommand_matches("list") {
        commands::list::execute(matches);
    }
}

src/cli.rs

use clap::{App, Arg, Command};

pub fn build_cli() -> Command<'static> {
    Command::new("my_cli_app")
        .version("0.1.0")
        .about("A simple CLI application")
        .subcommand(
            Command::new("add")
                .about("Adds a new item")
                .arg(Arg::new("item").required(true).takes_value(true)),
        )
        .subcommand(
            Command::new("remove")
                .about("Removes an item")
                .arg(Arg::new("item").required(true).takes_value(true)),
        )
        .subcommand(Command::new("list").about("Lists all items"))
}

src/commands/mod.rs

pub mod add;
pub mod remove;
pub mod list;

src/commands/add.rs

use clap::ArgMatches;

pub fn execute(matches: &ArgMatches) {
    let item = matches.value_of("item").unwrap();
    println!("Adding item: {}", item);
    // 逻辑添加到实际存储
}

src/commands/remove.rs

use clap::ArgMatches;

pub fn execute(matches: &ArgMatches) {
    let item = matches.value_of("item").unwrap();
    println!("Removing item: {}", item);
    // 逻辑从实际存储中删除
}

src/commands/list.rs

pub fn execute() {
    println!("Listing all items");
    // 列出所有存储的项目
}

详细学习内容与代码示例

1. Web开发

使用Rocket框架构建Web应用:

Cargo.toml

[dependencies]
rocket = "0.5.0-rc.1"

src/main.rs

#[macro_use] extern crate rocket;

#[get("/")]
fn index() -> &'static str {
    "Hello, world!"
}

#[launch]
fn rocket() -> _ {
    rocket::build().mount("/", routes![index])
}

使用Diesel进行数据库操作:

Cargo.toml

[dependencies]
diesel = { version = "1.4.8", features = ["sqlite"] }
dotenv = "0.15.0"

[dependencies.rocket_contrib]
version = "0.5.0-rc.1"
features = ["diesel_sqlite_pool"]

src/main.rs

#[macro_use] extern crate diesel;
#[macro_use] extern crate rocket;

use rocket::fairing::AdHoc;
use rocket::serde::json::Json;
use rocket::serde::{Serialize, Deserialize};

mod schema;
mod models;

#[database("sqlite_db")]
struct DbConn(diesel::SqliteConnection);

#[get("/items")]
async fn get_items(conn: DbConn) -> Json<Vec<models::Item>> {
    use crate::schema::items::dsl::*;

    let results = conn.run(|c| items.load::<models::Item>(c)).await.unwrap();
    Json(results)
}

#[launch]
fn rocket() -> _ {
    rocket::build()
        .attach(DbConn::fairing())
        .attach(AdHoc::on_ignite("Database Migrations", run_migrations))
        .mount("/", routes![get_items])
}

async fn run_migrations(rocket: rocket::Rocket<rocket::Build>) -> rocket::Rocket<rocket::Build> {
    use diesel_migrations::embed_migrations;
    embed_migrations!();
    DbConn::get_one(&rocket)
        .await
        .expect("database connection")
        .run(|c| embedded_migrations::run(c))
        .await
        .expect("can run migrations");
    rocket
}

src/schema.rs

table! {
    items (id) {
        id -> Integer,
        name -> Text,
    }
}

src/models.rs

use diesel::prelude::*;
use rocket::serde::{Serialize, Deserialize};

#[derive(Queryable, Serialize, Deserialize)]
pub struct Item {
    pub id: i32,
    pub name: String,
}

2. 系统编程

编写系统级工具:

文件监控工具:

use notify::{Watcher, RecursiveMode, watcher};
use std::sync::mpsc::channel;
use std::time::Duration;

fn main() {
    let (tx, rx) = channel();

    let mut watcher = watcher(tx, Duration::from_secs(10)).unwrap();
    watcher.watch("/path/to/watch", RecursiveMode::Recursive).unwrap();

    loop {
        match rx.recv() {
            Ok(event) => println!("{:?}", event),
            Err(e) => println!("watch error: {:?}", e),
        }
    }
}

3. 嵌入式开发

使用no_std进行嵌入式编程:

Cargo.toml

[dependencies]
panic-halt = "0.2.0"

src/main.rs

#![no_std]
#![no_main]

extern crate panic_halt;

use cortex_m_rt::entry;

#[entry]
fn main() -> ! {
    loop {
        // LED闪烁逻辑
    }
}

4. 网络编程

编写一个简单的HTTP服务器:

use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
use std::fs;

fn main() {
    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();

    for stream in listener.incoming() {
        let stream = stream.unwrap();
        handle_connection(stream);
    }
}

fn handle_connection(mut stream: TcpStream) {
    let mut buffer = [0; 1024];
    stream.read(&mut buffer).unwrap();

    let contents = fs::read_to_string("hello.html").unwrap();
    let response = format!("HTTP/1.1 200 OK\r\n\r\n{}", contents);

    stream.write(response.as_bytes()).unwrap();
    stream.flush().unwrap();
}

5. 并发编程

使用tokio进行异步编程:

Cargo.toml

[dependencies]
tokio = { version = "1", features = ["full"] }

异步TCP服务器:

use tokio::net::TcpListener;
use tokio::prelude::*;

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:6142").await?;

    loop {
        let (mut socket, _) = listener.accept().await?;

        tokio::spawn(async move {
            let mut buf = [0; 1024];

            loop {
                let n = match socket.read(&mut buf).await {
                    Ok(n) if n == 0 => return,
                    Ok(n) => n,
                    Err(e) => {
                        eprintln!("failed to read from socket; err = {:?}", e);
                        return;
                    }
                };

                if let Err(e) = socket.write_all(&buf[0..n]).await {
                    eprintln!("failed to write to socket; err = {:?}", e);
                    return;
                }
            }
        });
    }
}

WebAssembly与前端开发

目标:掌握Rust在WebAssembly和前端开发中的应用,编写高效的WebAssembly模块和前端应用。

学习内容:

  • WebAssembly基础:学习WebAssembly的基本概念和工作原理。
  • Rust与WebAssembly:使用wasm-bindgen和wasm-pack工具链编写和构建WebAssembly模块。
  • 与JavaScript互操作:学习如何在WebAssembly模块中调用JavaScript代码,反之亦然。
  • 前端框架:使用Yew或Seed等前端框架,编写高效的Rust前端应用。

示例:编写一个简单的WebAssembly模块并与JavaScript互操作

Cargo.toml

[dependencies]
wasm-bindgen = "0.2"

[lib]
crate-type = ["cdylib"]

src/lib.rs

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn greet(name: &str) -> String {
    format!("Hello, {}!", name)
}

构建和运行WebAssembly模块

https://rustwasm.github.io/docs/wasm-pack/

$ wasm-pack build 

区块链与加密技术

目标:学习Rust在区块链和加密技术中的应用,编写高效的区块链和加密算法。

学习内容:

  • 区块链基础:了解区块链的基本概念和工作原理。
  • Rust区块链开发:使用substrate框架开发区块链应用。
  • 加密算法:掌握常用的加密算法,如RSA、AES和哈希算法,编写安全的加密代码。

示例:使用substrate编写一个简单的区块链模块

$ substrate-node-new blockchain_project
$ cd blockchain_project
$ cargo build --release

src/lib.rs

#![cfg_attr(not(feature = "std"), no_std)]

use frame_support::{decl_module, decl_storage, decl_event, dispatch};
use frame_system::ensure_signed;

pub trait Config: frame_system::Config {
    type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>;
}

decl_storage! {
    trait Store for Module<T: Config> as TemplateModule {
        Something get(fn something): Option<u32>;
    }
}

decl_event! {
    pub enum Event<T> where AccountId = <T as frame_system::Config>::AccountId {
        SomethingStored(u32, AccountId),
    }
}

decl_module! {
    pub struct Module<T: Config> for enum Call where origin: T::Origin {
        fn deposit_event() = default;

        #[weight = 10_000]
        pub fn do_something(origin, something: u32) -> dispatch::DispatchResult {
            let who = ensure_signed(origin)?;
            Something::put(something);
            Self::deposit_event(RawEvent::SomethingStored(something, who));
            Ok(())
        }
    }
}

学习资源

  • Building Web Applications with Rust
  • Rust CLI Book

这个计划旨在系统地学习Rust,从基础到高级,再到实战项目,帮助你全面掌握Rust编程。

Last Updated:
Contributors: rosendo
Prev
rust iterator
Next
生命周期(lifetime)