第七部分:Rust 项目实战
本部分通过两个实际项目案例展示 Rust 的应用场景与实现细节。第一个项目是命令行工具,演示如何解析命令行参数并处理文件内容;第二个项目是构建一个简单的 Web 服务,展示 Rust 在网络开发中的强大能力。
18. 实现一个简单的命令行工具
目标:开发一个 Rust 命令行工具,用于统计文本文件中的单词数量。
功能需求
- 接收命令行参数(文件路径)。
- 读取文件内容并统计单词数量。
- 支持可选参数,例如统计字符数量。
项目初始化
步骤 1:创建项目
使用 Cargo 创建新项目:
cargo new word_counter
cd word_counter
项目结构
word_counter/
├── Cargo.toml
└── src/
└── main.rs
实现命令行参数解析
使用 clap
库解析命令行参数。
代码实现
在 Cargo.toml
中添加依赖:
[dependencies]
clap = { version = "4.1", features = ["derive"] }
编辑 src/main.rs
:
use clap::Parser;
/// Simple program to count words or characters in a file
#[derive(Parser)]
#[command(author, version, about)]
struct Cli {
/// File path
file_path: String,
/// Count characters instead of words
#[arg(short, long)]
chars: bool,
}
fn main() {
let args = Cli::parse();
let content = std::fs::read_to_string(&args.file_path)
.expect("Failed to read file");
if args.chars {
println!("Character count: {}", content.chars().count());
} else {
println!("Word count: {}", content.split_whitespace().count());
}
}
运行工具
运行示例
运行以下命令:
cargo run -- text.txt
输出:
Word count: 42
使用字符统计:
cargo run -- text.txt --chars
输出:
Character count: 256
流程图:命令行工具执行流程
+-------------------------+
| 用户输入命令与参数 |
+-------------------------+
|
v
+-------------------------+
| 解析命令行参数 |
+-------------------------+
|
v
+-------------------------+
| 读取文件内容 |
+-------------------------+
|
v
+--------------------