当前位置:网站首页>Rust language - receive command line parameter instances
Rust language - receive command line parameter instances
2022-07-06 07:26:00 【A pig】
First cargo new minigrep Create a file called minigrep Project files for
cd minigrep Enter file
code . use vscode Open the file
We want to make the project look neat , stay main.rs Write call implementation , stay lib.rs Write method to achieve
Because the project needs , Create a poem.txt The file of
main.rs The code in
use std::env;
use std::process;
use minigrep::{Config, run};
fn main(){
let args:Vec<String> = env::args().collect();
let config = Config::new(&args).unwrap_or_else(|err|{
eprintln!("Problem parsing argument: {}", err);// Standard error output
process::exit(0);
});//Result The way to go unwrap_or_else() if Ok Then put Ok The median value is assigned to the previous variable
if let Err(e) = run(config){
eprintln!("Application error:{}", e);// Standard error output
process::exit(0);
}
}
// cargo run I poem.txt > output.txt Command can output the result of successful compilation to output.txt in
// And the wrong result passes eprintln! Output to terminal
lib.rs The code in
use std::fs;
use std::error::Error;
use std::env;
pub fn run(config:Config)->Result<(), Box<dyn Error>>{//() Representative return is null
let contents =
fs::read_to_string(config.filename)?;//? When an error occurs, return the error value to the caller of the function for processing
let result = {if config.case_sensitive{
search(&config.query, &contents)
}else{
search_case_insensitive(&config.query, &contents)
}
};
for line in result{
println!("{}", line);
}
Ok(())
}
impl Config{
pub fn new(args:&Vec<String>)->Result<Config, &str>{
if args.len()<3{
return Err("not enough arguments");
}
let q = args[1].clone();
let f = args[2].clone();
let r = env::var("CASE_INSENSITIVE").is_err();//CASE_INSENSITIVE=1 cargo run I poem.txt The command will output case insensitive lines
Ok(Config{
query:q,
filename:f,
case_sensitive:r,
})
}
}
pub struct Config{
pub query:String,
pub filename:String,
pub case_sensitive:bool,
}
pub fn search<'a>(query:&str, contents:&'a str)->Vec<&'a str>{
let mut result:Vec<&str> = vec![];
for line in contents.lines(){//lines Function returns each line of text
if line.contains(&query){//contains Function to determine whether the line contains a string slice and return bool type
result.push(line);
}
}
result
}
pub fn search_case_insensitive<'a>(query:&str, contents:&'a str)->Vec<&'a str>{
let mut result:Vec<&str> = vec![];
let query = query.to_lowercase();//to_lowercase Function to make the string slice lowercase
for line in contents.lines(){//lines Function returns each line of text
if line.to_lowercase().contains(&query){//contains Function to determine whether the line contains a string slice and return bool type
result.push(line);
}
}
result
}
#[cfg(test)]
mod tests{
use super::*;
#[test]
fn case_sensitive(){
let query = "duct";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";
assert_eq!(vec!["safe, fast, productive."],
search(query, contents));
}
#[test]
fn case_insensitive(){
let query = "rUsT";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust tape.";
assert_eq!(vec!["Rust:", "Trust tape."],
search_case_insensitive(query, contents));
}
}
Finally using cargo run I poem.txt > output.txt Command can output the result of successful compilation to output.txt in , And the wrong result passes eprintln! Output to terminal
边栏推荐
- 【MySQL学习笔记32】mvcc
- Jerry's general penetration test - do data transmission with app Communication [article]
- GET/POST/PUT/PATCH/DELETE含义
- Summary of Digital IC design written examination questions (I)
- CF1036C Classy Numbers 题解
- leecode-C語言實現-15. 三數之和------思路待改進版
- Multi attribute object detection on rare aircraft data sets: experimental process using yolov5
- Leetcode59. spiral matrix II (medium)
- After the hot update of uniapp, "mismatched versions may cause application exceptions" causes and Solutions
- 洛谷P4127 [AHOI2009]同类分布 题解
猜你喜欢
leetcode841. Keys and rooms (medium)
Oracle database 11gr2 uses TDE transparent data encryption to report an error ora28353. If you run to close the wallet, you will report an error ora28365. If you run to open the wallet, you will repor
1091: two or three things in childhood (multi instance test)
If Jerry needs to send a large package, he needs to modify the MTU on the mobile terminal [article]
Lesson 12 study notes 2022.02.11
Cookie技术&Session技术&ServletContext对象
The author is dead? AI is conquering mankind with art
Cookie Technology & session Technology & ServletContext object
Leetcode35. search the insertion position (simple, find the insertion position, different writing methods)
Ali's redis interview question is too difficult, isn't it? I was pressed on the ground and rubbed
随机推荐
TypeScript接口与泛型的使用
Simple and understandable high-precision addition in C language
Mise en œuvre du langage leecode - C - 15. Somme des trois chiffres - - - - - idées à améliorer
The best way to learn SEO: search engine
Methods for JS object to obtain attributes (. And [] methods)
js对象获取属性的方法(.和[]方式)
Résumé de la structure du modèle synthétisable
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
TypeScript 接口属性
Scala语言学习-08-抽象类
Force buckle day31
leecode-C语言实现-15. 三数之和------思路待改进版
Multi attribute object detection on rare aircraft data sets: experimental process using yolov5
C语言 简单易懂的高精度加法
学go之路(二)基本类型及变量、常量
mysql如何合并数据
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
qt颜色与字符串、uint相互转换
Supervisor usage document
Three no resumes in the software testing industry. What does the enterprise use to recruit you? Shichendahai's resume