当前位置:网站首页>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
边栏推荐
- C - Inheritance - polymorphism - virtual function member (lower)
- mysql如何合并数据
- Jerry needs to modify the profile definition of GATT [chapter]
- If Jerry needs to send a large package, he needs to modify the MTU on the mobile terminal [article]
- TypeScript接口与泛型的使用
- [MySQL learning notes 32] mvcc
- #systemverilog# 可综合模型的结构总结
- Win10 64 bit Mitsubishi PLC software appears oleaut32 DLL access denied
- Redis builds clusters
- Internal and external troubles of "boring ape" bayc
猜你喜欢
![[window] when the Microsoft Store is deleted locally, how to reinstall it in three steps](/img/57/ee979a7db983ad56f0df7345dbc91f.jpg)
[window] when the Microsoft Store is deleted locally, how to reinstall it in three steps

烧录场景下的源代码防泄密方案分享
![[MySQL learning notes 30] lock (non tutorial)](/img/9b/1e27575d83ff40bebde118b925f609.png)
[MySQL learning notes 30] lock (non tutorial)

TypeScript接口与泛型的使用

Leetcode59. spiral matrix II (medium)

How are the open source Netease cloud music API projects implemented?

SSM learning

剪映的相关介绍

学go之路(一)go的基本介绍到第一个helloworld

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
随机推荐
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
[MySQL learning notes 30] lock (non tutorial)
Markdown 中设置图片图注
杰理之蓝牙设备想要发送数据给手机,需要手机先打开 notify 通道【篇】
You deserve this high-value open-source third-party Netease cloud music player
Memory error during variable parameter overload
Leetcode35. search the insertion position (simple, find the insertion position, different writing methods)
可变参数重载时的内存错误
On the world of NDK (2)
Méthode d'obtention des propriétés de l'objet JS (.Et [] méthodes)
Scala语言学习-08-抽象类
Leetcode 78: subset
JMeter performance test steps practical tutorial
Introduction to the basics of network security
Significance and measures of encryption protection for intelligent terminal equipment
MVVM of WPF
Typescript void base type
Seriously recommend several machine learning official account
[dictionary tree] [trie] p3879 [tjoi2010] reading comprehension
Set picture annotation in markdown