当前位置:网站首页>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

原网站

版权声明
本文为[A pig]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131923514204.html