当前位置:网站首页>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
边栏推荐
- Do you really think binary search is easy
- Ble of Jerry [chapter]
- Uni app third party package configuration network request
- Typescript interface and the use of generics
- TypeScript void 基础类型
- Ble of Jerry [chapter]
- Structure summary of SystemVerilog integrable model
- When the Jericho development board is powered on, you can open the NRF app with your mobile phone [article]
- Supervisor usage document
- SSM learning
猜你喜欢
杰理之蓝牙设备想要发送数据给手机,需要手机先打开 notify 通道【篇】
Set picture annotation in markdown
Detailed explanation | detailed explanation of internal mechanism of industrial robot
杰理之AD 系列 MIDI 功能说明【篇】
SSM学习
navicat如何导入MySQL脚本
Solution to the problem of breakthrough in OWASP juice shop shooting range
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
Mise en œuvre du langage leecode - C - 15. Somme des trois chiffres - - - - - idées à améliorer
leetcode704. Binary search (find an element, simple, different writing)
随机推荐
Ble of Jerry [chapter]
杰理之需要修改 gatt 的 profile 定义【篇】
Summary of Digital IC design written examination questions (I)
C - Inheritance - polymorphism - virtual function member (lower)
js對象獲取屬性的方法(.和[]方式)
JDBC学习笔记
OpenJudge NOI 2.1 1661:Bomb Game
[JDBC] quick start tutorial
ORACLE列转行--某字段按指定分隔符转多行
How to delete all the words before or after a symbol in word
jmeter性能测试步骤实战教程
Internal and external troubles of "boring ape" bayc
Go learning --- use reflection to judge whether the value is valid
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
Emo diary 1
Ble of Jerry [chapter]
Force buckle day31
Cookie Technology & session Technology & ServletContext object
杰理之普通透传测试---做数传搭配 APP 通信【篇】
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