参考:https://www.bilibili.com/video/BV1hp4y1k7SV
模仿grep写一个小项目
12.1 接受命令行参数
- 创建项目
cargo new minigrep
- 要在终端输入接受命令行参数,希望用户有如下输入
cargo run XXX XXXXX.txt
use std::env;
fn main() {
let args:Vec<String>=env::args().collect();
println!("{:?}",args);
}
输出
cargo run
["target\\debug\\minigrep.exe"]
$ cargo run hello myfile.txt
Finished dev [unoptimized + debuginfo] target(s) in 0.00s
Running `target\debug\minigrep.exe hello myfile.txt`
["target\\debug\\minigrep.exe", "hello", "myfile.txt"]
但是env::args0无法处理非法字符,会发生恐慌
TODO: 可以考虑用env::args_os()来解决,此处暂不考虑
- 接受两个参数并保存
use std::env;
fn main() {
let args:Vec<String>=env::args().collect();
println!("{:?}",args);
let query =&args[1];
let filename=&args[2];
println!("Search for '{}'",query);
println!("In file {}",filename);
}
$ cargo run hello myfile.txt
Compiling minigrep v0.1.0 (D:\Workplace\Rust\study\minigrep)
Finished dev [unoptimized + debuginfo] target(s) in 0.14s
Running `target\debug\minigrep.exe hello myfile.txt`
["target\\debug\\minigrep.exe", "hello", "myfile.txt"]
Search for 'hello'
In file myfile.txt
12.2 读取文件
use std::env;
use std::fs;//处理和文件相关的任务
fn main() {
let args:Vec<String>=env::args().collect();
let query =&args[1];
let filename=&args[2];
println!("Search for '{}'",query);
println!("In file {}",filename);
let contents=fs::read_to_string(filename)
.expect("Someing went wrong reading the file");
println!("With text:\n{}",contents);
}
$ cargo run abc story.txt
Finished dev [unoptimized + debuginfo] target(s) in 0.00s
Running `target\debug\minigrep.exe abc story.txt`
Search for 'abc'
In file story.txt
With text:
Working from home has become increasingly common, but it can be a challenge to stay productive in this environment.
To maintain focus, it is important to establish a designated workspace that is free of distractions.
It is also helpful to set specific work hours and take regular breaks throughout the day to stay energized.
Minimizing distractions such as social media notifications or TV shows can help increase productivity.
Finally, staying connected with colleagues through video conferencing tools can prevent feelings of isolation.
By implementing these tips, individuals can stay productive while working from home and maintain a healthy work-life balance.
12.3 重构:改进模块
存在问题:
- 主函数负责的任务太多了
- 程序代码最好一个函数负责一个功能
- 字段太多太杂难以管理–创建struct管理
- 错误打印的信息不清晰错误处理不好,难以维护,放置一处处理好
二进制程序关注点分离的指导性原则
- 将程序拆分为 main.rs 和 librs,将业务逻辑放入 lib.rs
- 当命令行解析逻辑较少时,将它放在main.rs也ok
- 当命令行解析逻辑变复杂时,需要将它从 main.rs 提取到lib.rs
main负责运行
lib负责处理业务逻辑
经过上述拆分,留在 main 的功能有:
- 使用参数值调用命令行解析逻辑
- 进行其它配置
- 调用lib.rs中的run函数
- 处理run函数可能出现的错误
fn main() {
let args:Vec<String>=env::args().collect();
let (query,filename)=parse_config(&args);
...
}
fn parse_config(args:&[String])->(&str,&str){
let query=&args[1];
let filename=&args[2];
(query,filename)
}
但是两个配置参数放在一个元组里,没有关联
-----放在一个struct里面
use std::env;
use std::fs;//处理和文件相关的任务
fn main() {
let args:Vec<String>=env::args().collect();
let config=parse_config(&args);
let contents=fs::read_to_string(config.filename)
.expect("Someing went wrong reading the file");
println!("With text:\n{}",contents);
}
struct Config{
query:String,
filename:String,
}
fn parse_config(args:&[String])->Config{
let query=args[1].clone();
let filename=args[2].clone();
Config {
query, filename }
}
clone虽然低效,但是简洁性强
把函数和config相关联
use std::env;
use std::fs;//处理和文件相关的任务
fn main() {
let args:Vec<String>=env::args().collect();
let config=Config::new(&args);
let contents=fs::read_to_string(config.filename)
.expect("Someing went wrong reading the file");
println!("With text:\n{}",contents);
}
struct Config{
query:String,
filename:String,
}
impl Config{
fn new (args:&[String])->Config{
let query=args[1].clone();
let filename=args[2]

文章详细介绍了如何使用Rust编程语言,通过命令行参数接受用户输入,读取文件内容,并实现简单的文本搜索功能。在开发过程中,进行了代码重构,改进了错误处理,并应用了测试驱动开发(TDD)方法,增加了对大小写敏感/不敏感搜索的支持。此外,还讨论了如何利用环境变量和标准错误输出来增强程序的可用性和错误报告。
最低0.47元/天 解锁文章
1223

被折叠的 条评论
为什么被折叠?



