Rust

Rust IO Demo

A Rust IO Operation Demo #

use colored::Colorize;
use csv::ReaderBuilder;
use csv::WriterBuilder;
use serde::Deserialize;
use serde::Serialize;
use std::error::Error;
use std::fs::File;
use std::path::Path;
use std::time::{SystemTime, UNIX_EPOCH};
use std::{env, process};

#[derive(Debug, Deserialize, Serialize)]
struct Row {
    name: String,
    age: u32,
    city: String,
}

fn file_check(args: &Vec<String>) {
    if args.len() < 2 {
        println!("{}", "请输入CSV文件路径".yellow());
        process::exit(1);
    }

    let file_path = Path::new(&args[1]);

    if file_path.exists() && file_path.is_file() {
        println!("{}", "文件存在".green());
    } else {
        println!("{}", "文件不存在,请输入正确的文件路径".red());
        process::exit(1);
    }
}

fn main() -> Result<(), Box<dyn Error>> {
    println!("{} \n", "正在处理...".green());

    let args: Vec<String> = env::args().collect();
    file_check(&args);

    // 读取 CSV 文件
    let file = File::open(&args[1])?;
    let mut reader = ReaderBuilder::new().has_headers(true).from_reader(file);
    let mut rows: Vec<Row> = reader.deserialize().collect::<Result<_, _>>()?;

    let mut rows_output_ok: Vec<Row> = vec![];
    let mut rows_output_warn: Vec<Row> = vec![];

    for row in &mut rows {
        println!("Current Row: {} {} {}", row.name, row.age, row.city);

        if row.city.len() > 5 {
            println!("超过限定 {}", row.city);
            rows_output_ok.push(Row {
                name: row.name.to_string(),
                age: row.age,
                city: row.city.to_string(),
            });
        } else {
            println!("低于限定 {}", row.city);
            rows_output_warn.push(Row {
                name: row.name.to_string(),
                age: row.age,
                city: row.city.to_string(),
            });
        }
    }

    let now = SystemTime::now();
    let duration_since_epoch = now
        .duration_since(UNIX_EPOCH)
        .expect("Failed to get duration since epoch");
    let milliseconds = duration_since_epoch.as_millis() as u64;
    let output_ok = format!("output_ok_{}.csv", milliseconds);
    let output_warn = format!("output_warn_{}.csv", milliseconds);

    // 写入新的 CSV 文件
    let mut ok_writer = WriterBuilder::new()
        .has_headers(true)
        .from_path(&output_ok)?;

    for row in &rows_output_ok {
        ok_writer.serialize(row)?;
    }

    ok_writer.flush()?;
    println!("写入文件 {} 完成", &output_ok.red());

    let mut warn_writer = WriterBuilder::new()
        .has_headers(true)
        .from_path(&output_warn)?;

    for row in &rows_output_warn {
        warn_writer.serialize(row)?;
    }

    warn_writer.flush()?;
    println!("写入文件 {} 完成", &output_warn.red());

    Ok(())
}

0x00 Rust Review and Calibration

Rust 知识复习与校准 #

本文档用于复习知识结构、校准内容准确性、并标记待补充知识点。
最后更新:2025-02

一、知识结构总览 #

当前 0x045-Rust 目录覆盖了 The Rust Book 主线 + 部分进阶与生态,结构如下。

1. 基础 (Fundamentals) #

文档内容概要
0x01 Rust overview环境、Cargo、生态(CLI/GUI/后端/WASM)、国内源、文档注释
0x03a Data Types标量(整型/浮点/bool/char)、复合(tuple/array)、字面量
0x03b Functions函数定义、语句与表达式、返回值
0x03c Control Flowifloop/while/for
0x05 Struct结构体定义、字段、方法、关联函数
0x06 Enums and Pattern Matching枚举变体、matchif let、模式

2. 所有权与类型系统 (Core) #

文档内容概要
0x04 Ownership三规则、move、Copy、drop、函数传参
0x04 References and Borrowing引用、借用规则、可变/不可变、切片、data race
0x10a Generic Types, Traits, and Lifetimes泛型 struct/enum/impl、泛型函数
0x10b Traitstrait 定义与实现、trait bounds、多态
0x10c Lifetimes显式生命周期注解、struct/impl、'static、与泛型组合

3. 工程与错误 (Project & Error) #

文档内容概要
0x07 Packages, Crates, and Modulespackage/crate/mod、路径、use、workspace
0x08a Common CollectionsVec 等
0x08b StringString 与 str、UTF-8
0x08c Hash MapHashMap
0x09 Error HandlingResult/Option?unwrap/expectmain 返回 Result

4. 进阶 (Advanced) #

文档内容概要
0x11 Automated Tests测试(未在本次逐字审阅)
0x13a Iterators and Closures闭包、捕获、Fn/FnMut/FnOnce、move
0x13b Iterators惰性、iter/into_iter/iter_mut、map/filter/collect/sum
0x15 Smart PointersBox、Deref、Drop、Rc、RefCell、内部可变性
0x16 Concurrency线程、JoinHandle、move、mpsc、Mutex、Arc
0x10c Lifetimes见上
Macros声明宏 vs 过程宏(简述)
Unsafe Rust五类 unsafe 操作列举

5. 生态与工具 (Overview 中) #

  • CLI:clap、structopt、termion、serde 等
  • GUI:Tauri、Iced、Dioxus、Slint、egui 等
  • 后端:Rocket、Actix、Axum、Pingora 等
  • WASM:wasm-bindgen、wasm-pack

二、校准项(已修正与建议) #

已修正 #

  1. 0x01-Rust overview.md

    ...

0x01 Rust Overview

Rust #

Review

  1. 2021/09/05
  2. 2024/03/02
  3. 2024/06/11
  4. 2025-06-14

Overview #

Rust is a modern system programming language focused on performance, safety, and concurrency. It accomplishes these goals without having a garbage collector, making it a useful language for a number of use cases other languages aren’t good at. Its syntax is similar to C++, but Rust offers better memory safety while maintaining high performance.

...

0x17 Async Rust

Async Rust #

Review: 2025-02

一、与「线程并发」的区别 #

  • 0x16 Concurrency 讲的是 std::thread:多线程 + channel + Mutex/Arc,适合 CPU 密集或少量 OS 线程。
  • Async Rust协作式多任务:在少量 OS 线程上跑大量异步任务,适合 I/O 密集(网络、文件、定时器)。不替代线程,而是另一种并发模型。

二、核心概念 #

  • Future:表示“将来会产出某个值”的 trait。异步函数返回 impl Future,需要被 poll 才会推进。
  • async / awaitasync fn 返回一个 Future;.await 在 Future 上等待完成而不阻塞线程。
  • Executor / Runtime:负责 poll 多个 Future、在 I/O 就绪时唤醒。Rust 标准库只提供 Future trait,不提供运行时;常用 Tokioasync-std
  • Pin:保证 Future 在内存中不移动,以便自引用结构能安全存在。多数写业务代码时由 async fn/async move 自动处理。

三、简单示例 #

use std::time::Duration;

// 需要运行时,例如 tokio
// #[tokio::main]
// async fn main() {
//     let out = fetch_and_print().await;
// }

async fn fetch_and_print() -> String {
    tokio::time::sleep(Duration::from_secs(1)).await;
    "done".to_string()
}

四、Send 与 Sync 在异步中的意义 #

  • 若 Future 需要跨 await 点被其他任务在不同线程里 poll,则该 Future 必须实现 Send
  • async 块或 async fn 里持有的数据若跨 .await,通常也需要是 Send(取决于运行时是否多线程)。
  • Sync:若 &T 能安全跨线程共享,则 T: Sync。多线程运行时里共享状态常用 Arc<Mutex<T>> 等,其要求内部 T 满足 Send(有时还有 Sync)。

五、学习与参考 #

Reference #

  1. https://rust-lang.github.io/async-book/
  2. https://tokio.rs/