当前位置:网站首页>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
边栏推荐
- leetcode1020. Number of enclaves (medium)
- Crawling exercise: Notice of crawling Henan Agricultural University
- 【JDBC】快速入门教程
- word中把带有某个符号的行全部选中,更改为标题
- C语言 简单易懂的高精度加法
- Three treasures of leeks and Chinese men's football team
- How can word delete English only and keep Chinese or delete Chinese and keep English
- JMeter performance test steps practical tutorial
- 位运算异或
- Week6 weekly report
猜你喜欢
Fundamentals of C language 9: Functions
JDBC学习笔记
数字IC设计笔试题汇总(一)
leetcode704. Binary search (find an element, simple, different writing)
杰理之AD 系列 MIDI 功能说明【篇】
Week6 weekly report
The way to learn go (I) the basic introduction of go to the first HelloWorld
If Jerry needs to send a large package, he needs to modify the MTU on the mobile terminal [article]
jmeter性能测试步骤实战教程
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
随机推荐
Résumé de la structure du modèle synthétisable
word删除括号里内容
If Jerry's Bluetooth device wants to send data to the mobile phone, the mobile phone needs to open the notify channel first [article]
How can word delete English only and keep Chinese or delete Chinese and keep English
杰理之普通透传测试---做数传搭配 APP 通信【篇】
leetcode1020. Number of enclaves (medium)
You deserve this high-value open-source third-party Netease cloud music player
[JDBC] quick start tutorial
杰理之开发板上电开机,就可以手机打开 NRF 的 APP【篇】
【MySQL学习笔记32】mvcc
Scala language learning-08-abstract classes
Relevant introduction of clip image
How MySQL merges data
word中如何删除某符号前面或后面所有的文字
[window] when the Microsoft Store is deleted locally, how to reinstall it in three steps
【JDBC】快速入门教程
多线程和并发编程(二)
Lesson 12 study notes 2022.02.11
Project GFS data download
Oracle column to row -- a field is converted to multiple rows according to the specified separator